Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Check if user exists before creating new user djangorestframework
So far I have -> serializer: class UserSerializer(serializers.ModelSerializer): """Serializer to map the model instance into json format.""" class Meta: """Map this serializer to a model and their fields.""" model = User fields = ('id','username', 'mobile', 'password', 'first_name','last_name','middle_name','profile_pic','short_bio','friends_privacy','address_1','address_2','city','state','country','pin','verification_code','is_active','is_blocked','is_reported','date_created','date_modified') # ADD 'owner' extra_kwargs = {'password': {'write_only': True}} read_only_fields = ('date_created', 'date_modified','is_staff', 'is_superuser', 'is_active', 'date_joined',) def create(self, validated_data): mobile_ = validated_data['mobile'] password_ = validated_data['password'] username_ = validated_data['username'] motp = self.context['request'].GET['motp'] eotp = self.context['request'].GET['eotp'] email_ = self.context['request'].GET['email'] mflag = api.views.checkOTP_(mobile_,motp) eflag = api.views.checkOTP_(email_,eotp) if (mflag and eflag): user = User( username=username_, email =email_, password = make_password(password_), mobile = mobile_, ) user.set_password(validated_data['password']) user.save() return user view: class UserView2(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer model = User def get_permissions(self): # allow non-authenticated user to create via POST return (AllowAny() if self.request.method == 'POST' else IsStaffOrTargetUser()), I need to check for OTP of mobile and email and also if a user with same mobile or email already exists. If user already exists return a json response with error: already exists!. If user is new and OTP is wrong again raise an error. If user is new and OTP is correct, create an account. Problem here is I tried to add the function to check for otp … -
Filter response by POST request Django Rest-framewrok wirh foreign keys
My models: FormField: class FormField(models.Model): phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") fieldName = models.CharField(max_length=50) text = 'text' email = 'email' phone = PhoneNumberField() date = models.DateTimeField TYPE_OF_FIELD_CHOICE = ( (text, 'text'), (email, 'example@email.mail'), (phone, '+9123456789'), (date, '2017-01-01') ) field_type = models.CharField(max_length=25, choices=TYPE_OF_FIELD_CHOICE, default=text) def __str__(self): return self.fieldName FormPattern: class FormPattern(models.Model): formName = models.CharField(max_length=50) formFields = models.ManyToManyField(FormField) def __str__(self): return self.formName I am using REST django framework. I need to filter my response data by my POST request, that look like this: formpatterns/get_from?f_name1=value1&f_name2=value2 if f_name1 = fieldName in some FormPattern, i need to give response with this FormPattern formName. I already have serializator that work with choices and i can GET list all my FormPattern class FormSerializer(serializers.ModelSerializer): formName = serializers.CharField() formFields = serializers.SlugRelatedField( many=True, read_only=True, slug_field='field_type' ) class Meta: model = FormPattern fields = ('formName', 'formFields') my method in views.py: @api_view(['GET', 'POST']) @parser_classes((JSONParser,)) def form_list(request): if request.method == 'GET': forms = FormPattern.objects.all() serializer = FormSerializer(forms, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = FormFieldSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(FormPattern.serializer.data) else: return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST) POST just saving another FormPattern in my example. How need i edit this to get … -
getting "IntegrityError: NOT NULL constraint failed" in django 1.10 on unit test which were passing in Django 1.9
while calling Test Models save() i am getting this error self.created_by super(Test, self).save() *** IntegrityError: NOT NULL constraint failed: itests_test.created_by_id even though created_by_id is not null -
How could I use an HTML code to store data in a django based app?
So I have been trying to design an app that can take the file input from two csvs, then combine them into a dataframe and analyze them. The python function to do this is done, but there is an issue with uploading them onto the app. The django based app system that I am writing the app on has gizmos, but none of the gizmos are used for file input. So I put this code in the django template: <div class="gauge-data-upload"> <label class="control-label" for="gauge-data-upload-input">Recorded Gauge Data</label> <input id="gauge-data-upload-input" name="gauge-data-upload-input" type="file" accept=".txt,.csv"> <p class="help-block hidden">Must select file to submit!</p> </div> But I am uncertain how to link this html code to the controllers page (a page of python classes) This is what my controller for this particular django template looks like. @login_required() def add_gauge_data(request): """ Controller for the Add Dam page. """ # Handle form submission if request.POST and 'add-button' in request.POST: # Get values has_errors = False #Define Form Gizmos add_button = Button( display_text='Add', name='add-button', icon='glyphicon glyphicon-plus', style='success', attributes = {'form': 'add-gauge-data-form'}, submit = True ) cancel_button = Button( display_text='Cancel', name='cancel-button', href=reverse('statistics_calc:home') ) context = { 'add_button': add_button, 'cancel_button': cancel_button, } return render(request, 'statistics_calc/add_gauge_data.html', context) Will I need to write … -
How can I authenticate user both in websockets and REST using Django and Angular 4?
I would like to authenticate user both in websockets and REST using Django and Angular 4. I have created registration based on REST API. User after creating an account and log in can send messages to backend using websockets. My question is how can I find out that the authenticated user by REST API (I use Tokens) is the same user who sends messages? I don't think that sending Token in every websocket message would be a good solution. consumers.py: def msg_consumer(message): text = message.content.get('text') Message.objects.create( message=text, ) Group("chat").send({'text': text}) channel_session_user_from_http def ws_connect(message): message.reply_channel.send({"accept": True}) Group("chat").add(message.reply_channel) message.reply_channel.send({ "text": json.dumps({ 'message': 'Welcome' }) }) @channel_session_user def ws_receive(message): message.reply_channel.send({"accept": True}) print("Backend received message: " + message.content['text']) Message.objects.create( message = message.content['text'], ) Channel("chat").send({ "text": json.dumps({ 'message': 'Next message' }) }) @channel_session_user def ws_disconnect(message): Group("chat").discard(message.reply_channel) -
Django Models - How to add other objects of a Foreign Key
It has been difficult to find how to add in a table more them one column from other table (foreign key), see below: Models.py: class Operator(models.Model): user_id = models.OneToOneField(User) operator_name = models.CharField(max_length=100) cnpj = models.CharField(max_length=14) def __str__(self): return self.operator_name class Service(models.Model): operator_id = models.ForeignKey(Operator, on_delete=models.CASCADE) service_type = models.ForeignKey(ServiceType, on_delete=models.CASCADE) service_name = models.CharField(max_length=100) short_descrip = models.CharField(max_length=100) description = models.CharField(max_length=400) price = models.IntegerField(default=0) address = models.CharField(max_length=200) def __str__(self): return self.service_name Views.py def myagency(request): data = serializers.serialize("json", Service.objects.all()) return HttpResponse(json.dumps(data), content_type="application/json") In the JSON response I got: pk: 1 operator_id: 1 service_type: 3 ... I would like receive: pk: 1 operator_id: 1 operator_name: "operator_example" service_type: 3 ... Summarizing: I would like to include in the table "Service" the "Primary Key" and "operator_name" objects from the table "Operator". Does anybody know how to do this? Thanks! -
Issue with DecimalField,max_digits of django models
I have declared below field in models.py "marks = models.DecimalField(max_digits=2, decimal_places=2, default=3.0)" At backend table structure is | Field | Type | Null | Key | Default | Extra | | marks| float(3,1) | NO | | 1.0 | | So here default value 3.0 will try to save as 3.00 (decimal places=2) at backend and there will be no space to store left side value 3 right? For above case,when I give max_digits=3 or decimal_places=1 it is working. Please help me,what exactly happening here from django to mysql db flow? -
Django loaddata does not create m2m relations
I'm upgrade django from 1.8.4 to 1.11.6 and encountered problem. I have two models: class File(models.Model): title = models.CharField(max_length=128, verbose_name=_('title')) description = models.CharField( max_length=255, blank=True, null=True, verbose_name=_('description') ) class Task(models.Model): output_data = models.ManyToManyField( File, blank=True, verbose_name=_('output_data') ) I'm running manage.py loaddata with the following data for models above: files.json: [ { "fields": { "description": "", "title": "Data file 2", }, "model": "files.file", "pk": 2 } ] tasks.json: [ { "fields": { "output_data": [2] }, "model": "tasks.task", "pk": 1 } ] loaddata creates file and task, but not create m2m relation. Before the update everything worked fine. -
'social' is not a registered namespace when integrating social_django
I know similar questions have been asked before, but none of them seemed quite the same as my situation. The error I receive looks like this: Environment: Request Method: GET Request URL: http://web/login/auth0 Django Version: 1.10 Python Version: 3.5.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'social_django', 'my_app.apps.authentication'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/usr/local/lib/python3.5/site-packages/django/urls/base.py" in reverse 77. extra, resolver = resolver.namespace_dict[ns] During handling of the above exception ('social'), another exception occurred: File "/usr/local/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/usr/local/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.5/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.5/site-packages/social_django/utils.py" in wrapper 37. uri = reverse(redirect_uri, args=(backend,)) File "/usr/local/lib/python3.5/site-packages/django/urls/base.py" in reverse 87. raise NoReverseMatch("%s is not a registered namespace" % key) Exception Type: NoReverseMatch at /login/auth0 Exception Value: 'social' is not a registered namespace My application is Dockerized, and I am attempting to integrate Auth0 and social_django. I am using nginx, gunicorn, and postgres in my stack. I mainly followed this tutorial to get running: https://auth0.com/docs/quickstart/webapp/django I have social_django and the sub-application, authentication installed in my main settings file: # /src/my_app/settings.py INSTALLED_APPS = … -
ImportError: cannot import name '' import two model by themselves
I have stupid problem with Django and I don't have any idea why. I create new project test, in this project I create two apps (test1, test2). I add them to INSTALLED_APPS. In this apps I've add to models: test1.models: from django.db import models from test2.models import test2 # Create your models here. class test1(models.Model): pass test2.models: from django.db import models from test1.models import test1 # Create your models here. class test2(models.Model): pass Now I want to runserver but command gave me error: Unhandled exception in thread started by <function check_errors. <locals>.wrapper at 0x7f0881274620> Traceback (most recent call last): File "/home/krzysieqq/Projects/venvs/test/lib/python3.5/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/home/krzysieqq/Projects/venvs/test/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "/home/krzysieqq/Projects/venvs/test/lib/python3.5/site-packages/django/utils/autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "/home/krzysieqq/Projects/venvs/test/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/krzysieqq/Projects/venvs/test/lib/python3.5/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/home/krzysieqq/Projects/venvs/test/lib/python3.5/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/krzysieqq/Projects/venvs/test/lib/python3.5/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/home/krzysieqq/Projects/venvs/test/lib/python3.5/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/home/krzysieqq/Projects/venvs/test/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen … -
How to pass model instance to a form in a django wizard form?
I'm working with django-formtools and I need to create a 3 step form. I have the wizard working well but in the step 2 I need to render in the template the value of a model instance. views.py class PropertyWizard(SessionWizardView): def get_form_initial(self, step): initial = self.initial_dict.get(step, {}) if step == 'price': valuation = get_object_or_404(Valuation, user=self.request.user) initial.update({'valuation': valuation}) return initial If I print initial value it contains: {u'valuation': <Valuation: street test, 123>} urls.py url(r'^dashboard/properties/add/$', property_views.PropertyWizard.as_view(FORMS), name='add_property'), template.html Here I've tried this combinations: <h1>{{ initial }}</h1> <h1>{{ initial.valuation.creation_date }}</h1> But I've never seen anything. What am I doing wrong? -
Three Models in One Template
I'm new to Django and currently using version 1.11 with Python 3.6. I have three models in one template. Model 1 is my custom user which has a primary key called formattedusername. Model 2 is my access list which has a should create a 1 to many relationship with User on ntname. Model two has a foreign key to the reference table ReportList called report_id. Model 3 is my report list which has report_id as a primary key. I'm trying to create a views.py to link all three tables for one template. In my template I want to display for the current User all report_names listed in my access list model. Then another display of all available reports that the current User doesn't have access to, so the reports in Report List that don't exist in Access List. For my views.py I tried several variations of the following: def applicationdetail(request, ntname): user = get_object_or_404(User, pk=formattedusername) applicationlist = QvReportList.objects.all() applicationaccess = QVReportAccess.objects.filter(user=ntname) context = {'user' : request.user, 'applicationdetail' : applicationaccess} return render(request, 'accounts/profile.html', context=context) class IndexView(User): context_object_name = 'profile_list' template_name = 'contacts/index.html' queryset = User.objects.all() def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context['users'] = User.objects.filter(user=formattedusername) context['reportaccess'] = QVReportAccess.objects.filter(user=ntname) context['reportlist'] = QvReportList.objects.all() … -
trying to build a blog with dynamic formating
Can someone please point me in the direction of a resource to build a blog page with editing on a website? Websites like medium.com and stack overflow allow users to dynamically generate html elements. so add a picture here make the text go around the picture. Change this text to pink. format this text here etc how you do this? Im using angular and typescript my backend is a restful one in django. I'm not so much looking for plugins although I am sure they would be good to learn from, I am more trying to learn how to do it. -
Django-I am getting an syntax error for my one of my URLs even though not touching it. Not sure why [on hold]
I am doing my URLs in urls.py but getting an error even though not touching this certain URL. Can someone please tell me what I have done wrong? url(r'^contact/$', TemplateView.as_view(template_name="contact.html"), name="contact"), ^ SyntaxError: invalid syntax Also when I comment the contact URL out, I get the same error for an exact same "about" URL but with only "about" not "contact". If you need any other code please tell me. -
Error Traceback : Identity_set_unique = Symptom.objects.get(pk=pk). This is returning a ValueError
In my health app I am attempting to allow that user to enter patient symptom data and save it. Model logic I have three models created : Unique_Identity , Symptom, and Unique_Identity_Symptom In Unique_Identity there is the symptom_relation = models.ManyToManyField(Symptom, through = 'Unique_Identity_Symptom') field that connects to the Symptom model establishing a ManyToMany relationship In the Unique_Identity_Symptom model there are the patient = models.ForeignKey(Unique_Identity, related_name = 'symptoms') and symptom = models.ForeignKey(Symptom, related_name = 'reports') fields, however I am beginning to doubt the necessity of the Unique_Identity_Symptom model. Issue : THe problem is that each time I attempt to save the inserted data using the ModelForm created for the Symptom model I get this error : ValueError at /optic/Symptom-document/U849343/ invalid literal for int() with base 10: 'U849343' Traceback: File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/views/generic/base.py" in dispatch 88. return handler(request, *args, **kwargs) File "/Users/iivri.andre/vedic/Identity/optic/views.py" in post 113. Identity_set_unique = Symptom.objects.get(pk=pk) I have already tried this post, this, this and this but none of the answers are specific to my question. … -
Getting data from a uri django
I have a django view that takes in a json object and from that object I am able to get a uri. The uri contains an xml object. What I want to do is get the data from the xml object but I am not sure how to do this. I'm using django rest, which I am fairly inexperienced in using, but I do not know the uri until the I search the json object in the view. I have tried parsing it in the template but ran into CORS issues amongst others. Any ideas on how this could be done in the view? My main issue is not so much parsing the xml but how to get around the CORS issue which I have no experience in dealing with -
No module named django.core.urlresovers in django 2.0a1
Have recently upgraded from django 1.11.7 to django 2.0a1 and now cannot import reverse_lazy File "/home/silasi/Deprojecto/eljogo/jogos/views.py", line 8, in <module> from django.core.urlresolvers import reverse_lazy ModuleNotFoundError: No module named 'django.core.urlresolvers' -
How to add a confirmation page to an email form in django? Problems with django formtools or session data.
What I want to accomplish I want a page where user fill a form to send an email (to multiple recipients). Before sending, the user should see the hole email an all recipients and should confirm the sending or go back and edit it. What I have tried Using django formtools. https://github.com/django/django-formtools https://django-formtools.readthedocs.io/en/latest/ The Problem Formtools seems to only work if I derive the form from a model and I see no reason to do that. What I have else tried Saving the input in request.session. The Problem Recipients are a list of objects (ModelMultipleChoiceField). In request.session I can only save JSON data. Thus I can not serialize it. I could extract the email addresses of the recipients list but if the user wants to go back to the form I can not prefill the ModelMultipleChoiceField. So I ran out of ideas. -
Django model convert IntegerField to ForeingKey keeping date
i'm working ina project where I need to migrate an IntegerField to a ForeingKey to make it easier to do requests as: SKU_name, SKU_description, etc.. My models.py file has: class BasketTable(models.Model): """Basket table.""" # Generic data structure from the table internal_id = models.AutoField( primary_key=True, verbose_name="ID PK") internal_insertDate = models.DateTimeField( default=timezone.now, verbose_name="Data/Hora de Inserção") internal_updateDate = models.DateTimeField( default=timezone.now, verbose_name="Data/Hora de Atualização") # Specific fields from VTEX table List_Id = models.CharField( max_length=250, null=True, blank=True, verbose_name="ID da Lista") ListType_Id = models.CharField( max_length=250, null=True, blank=True, verbose_name="ID do Tipo de Lista") Alias = models.CharField(max_length=250, null=True, blank=True, verbose_name="Alias") SKU_Id = models.IntegerField(default=0, verbose_name="ID do SKU") Product_Id = models.IntegerField(default=0, verbose_name="ID do Produto") Quantity = models.IntegerField(default=0, verbose_name="Quantidade") I'm trying to change SKU_Id to SKU field name, setting: SKU = models.ForeignKey(SKUTable, db_column='Id', to_field='Id', null=True, verbose_name="ID do SKU") My SKU Id field has unique=True as needed according Django documentation. So, after this changes, I run python manage.py makemigrations command that results: class Migration(migrations.Migration): dependencies = [ ('products', '0013_auto_20171103_1412'), ('cil', '0016_auto_20171020_1546'), ] operations = [ migrations.RemoveField( model_name='baskettable', name='SKU_Id', ), migrations.AddField( model_name='baskettable', name='SKU', field=models.ForeignKey(db_column='Id', null=True, on_delete=django.db.models.deletion.CASCADE, to='products.SKUTable', to_field='Id', verbose_name='ID do SKU'), ), ] So, I changed this migration file to: class Migration(migrations.Migration): dependencies = [ ('products', '0013_auto_20171103_1412'), ('cil', '0016_auto_20171020_1546'), ] operations = [ … -
Acess Both Django-Filter DateFromToRangeFilter + RangeWidget Dates
I have a Django-Filter based on a model DateField: class MyModelFilter(FilterSet): triggerDate = DateFromToRangeFilter(widget=RangeWidget()) class Meta: model = MyModel fields = ['triggerDate'] I place this filter in my template like this: <th>{{ filter.form.triggerDate }}</th> This results in one text box where I can type a date and retrieve record matching that date. How do I access both the start and end dates of the filter? I tried this: <th>{{ filter.form.triggerDate }}</th> <th>{{ filter.form.triggerDate }}</th> This results in two inputs, but they force themselves to equal each other. -
django static files are sometimes not serving
Dear Stackoverflow community. I have for a while now been struggling with my static files during development in my Django project. The problem is mainly that my stylesheets are sometimes working and sometimes not. Example - my base.html's stylesheet base_style.css is always loading, but when I add a stylesheet for the file home.html which I have loaded through the jinja template tags It sometimes works and sometimes not, the same goes for my other views. Using python3 and Django 1.11.5 Here is my settings file (Static) = STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn") MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media_cdn") Here is my template Base.html = {% load static %} <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="apple-touch-icon" sizes="180x180" href="{% static 'img/favicons/apple-touch-icon.png' %}"> <link rel="icon" type="image/png" sizes="32x32" href="{% static 'img/favicons/favicon-32x32.png' %}"> <link rel="icon" type="image/png" sizes="16x16" href="{% static 'img/favicons/favicon-16x16.png' %}"> <link rel="manifest" href="{% static 'img/favicons/manifest.json' %}"> <link rel="mask-icon" href="{% static 'img/favicons/safari-pinned-tab.svg' %}" color="#5bbad5"> <meta name="theme-color" content="#ffffff"> <title>Leaf</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous"> <link href="https://fonts.googleapis.com/css?family=Roboto:100" rel="stylesheet"> <link rel="stylesheet" href="{% static 'mainapp/base_style.css' %}" type="text/css" /> </head> <body> <!-- NAVBAR --> <div class="container"> <nav class="navbar navbar-expand-lg navbar-light navbar-custom text-uppercase"> <img src="{% … -
Django rating model with m2m
I'm confused with my django models, My models: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) picture = models.ImageField(upload_to="photos/", default="photos/none/default.png") film = models.ManyToManyField(Film) class Film(models.Model): title = models.CharField(max_length=60) year = models.IntegerField(choices=YEARS) image = models.ImageField(upload_to="images/", default="images/none/blank_poster.jpg") def __str__(self): return self.title and now I trying to make a ratings for my film, when user adding a film to his list. I tried M2M with through, but it wasn't exactly what I wanted, because user could add the same film several times and another problem with it was remove single film from list. Now i thinking about additional models like this: class FilmRating(models.Model): user = models.ForeignKey(User) film = models.ForeignKey(Film) rate = models.IntegerField(choices=CHOICES) Im glad If you can point me to the correct way to solve this problem, In future I want probably to store all rating from users for set average rate. -
Django annonate Sum under a condition
I have a model which have fields like class Points(models.Model): player = models.ForeignKey(Player) points = models.IntegerField() datetime = models.Datetime() I want to get the sum of points on weekly basis with week start ie date. So let's say week start from 22nd October then it should accumulate point from 22nd October to 28th October. I tried the below query but it doesn't give me points on weekly basis since. The points aren't available for every player on each day so I need total weekly points scored. Points.objects.values('datetime').annonate(weekpoints=Sum('points')).order_by('-datetime') It returns points on daily basis not on weekly basis. -
Is there an easy way to create a user login?
I would like to have normal users (not admins) who can log in. By default when doing a project in Django it is enough to create a superuser and you can already authenticate and manage the site, also if I created a model named Question I can create, edit and delete questions from the admin dashboard (like in the tutorial part 2) adding just this code: from .models import Question admin.site.register(Question) I would like to replicate this, I mean, to have a similar login template with normal users and a dashboard where these normal users can see, create, edit and delete Question instances that belongs to them, ie., where they can manage only their questions, but obviously making them not be able to edit other users or groups, how could I do it? would it be difficult? Thanks! -
django forms - change the value of the fields
I have these models class Student(Model): student_no = CharField(max_length=10) name = CharField(max_length = 50) def __str__(self): return self.name class ClassList(Model): students = ForeignKey(Student) In forms: class ClassListForm(ModelForm): class Meta: fields = ['students'] When I render this, the template shows a select box with the students in it. However, the students are displayed based on what the def __str__() function contains. How do you change the values of the students field so that it will display their student_nos without changing the def __str__() function