尝试根据登录用户的用户名创建模型对象时出现“ WSGIRequest”错误 [英] 'WSGIRequest' Error when trying to create Model object based on username for logged in User

查看:182
本文介绍了尝试根据登录用户的用户名创建模型对象时出现“ WSGIRequest”错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 Alarm.username 设置为当前登录的用户名用户。这个问题与另一个查询相同,尽管我的代码在我提取了每个 Alarm 对象的位置详细信息。

I am attempting to set the Alarm.username to the username of the currently logged in User. The problem is identical to another query, although my code is a little different in that I extract location details for each Alarm object.

如何以及在何处集成该行: username = User.objects.get(username = self.request.username)在我的代码中?

How,and where, do I integrate the line: username=User.objects.get(username=self.request.username) in my code?

Request Method: POST
Request URL:    http://jqlc3gdp.apps.lair.io/login/set_alarm/
Django Version: 2.0
Exception Type: AttributeError
Exception Value:    
'WSGIRequest' object has no attribute 'username'
Exception Location: /mnt/project/weather_alarm/views.py in get_user_timezone, line 94



代码



Models.py

class User(models.Model):
    """ Model representing each User """
    username = models.CharField(max_length=20, unique=True)
    password = models.CharField(max_length=30, validators=[MinLengthValidator(8)])
    email = models.EmailField(max_length=254)
    first_name = models.CharField(max_length=20)
    last_name = models.CharField(max_length=20)


class Alarm(models.Model):
    """ Model representing each Alarm """
    alarm_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    username = models.ForeignKey(User, on_delete=models.CASCADE, null=True)         # null=True is TEMP
    timezone = models.CharField(max_length=30)
    city = models.CharField(max_length=30)
    country = models.CharField(max_length=30)
    time = models.DateTimeField()
    temp_conditional = models.BooleanField()
    surf_conditional = models.BooleanField()
    temp_max = models.FloatField(blank=True, null=True)
    temp_min = models.FloatField(blank=True, null=True)
    surf_max = models.FloatField(blank=True, null=True)
    surf_min = models.FloatField(blank=True, null=True)

Forms.py

class SetAlarmForm(ModelForm):
    ...    
    class Meta:
        model = Alarm
        exclude = ['username', 'timezone', 'city', 'country']

Views.py

class AlarmCreateView(LoginRequiredMixin, CreateView):
    model = Alarm
    form_class = SetAlarmForm
    template_name = 'weather_alarm/set_alarm.html'
    success_url = reverse_lazy('weather_alarm:confirm-alarm')
    login_url = "/login/"

    def form_valid(self, form):
        self.get_user_location(form)
        return super().form_valid(form)

    def get_user_location(self, form):
        """ Function to get User's location from IP and create Alarm object """
        ...
        alarm_object = Alarm.objects.create(
            alarm_id=uuid.uuid4(),
            username=User.objects.get(username=self.request.username),
            timezone=user_timezone,
            city=location.raw['address']['city'],
            country=location.raw['address']['country'],
            time=form.cleaned_data['time'].astimezone(pytz.timezone(user_timezone)),
            temp_conditional=form.cleaned_data['temp_conditional'],
            surf_conditional=form.cleaned_data['surf_conditional'],
            temp_max=form.cleaned_data['temp_max'],
            temp_min=form.cleaned_data['temp_min'],
            surf_max=form.cleaned_data['surf_max'],
            surf_min=form.cleaned_data['surf_min'],
        )
        alarm_object.save()


推荐答案

应为 self.request.user.username

username = User.objects.get(username=self.request.user.username)

或者因为 request.user 已经包含当前更好地使用用户对象:

Or since request.user already contains current user object better to use:

username = self.request.user

这篇关于尝试根据登录用户的用户名创建模型对象时出现“ WSGIRequest”错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆