Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I create a single-page application in Django using a websocket?
I'm making a site with Django and I'm a bit stuck with how to implement a single-page app part of the site, where the client asks the server via a websocket for different HTML-pages that it then renders. What I'm unsure of is where I would store the HTML that the client requests on the server. Note that the whole site isn't a single-page app, so the HTML I'm talking about here is separate from what is stored in the templates folder in my Django app. I was thinking about storing the HTML-files in the static folder, but couldn't figure out how to access that outside a template. In a template you could say this for example: {% load static %} <script src="{% static 'myapp/index.js' %}"></script> That isn't possible outside the template though, so I would appreciate help with that too. This wouldn't be a problem if I'd use a HTTP-request to get the HTML-files. If i'd use a HTTP-request I could just make a view that returns a template, but I wanna use a websocket and Django Channels since that, as far as I know, is faster. Maybe it's a bad idea to use a websocket for this though. -
Any way to exclude first form in formset from validation?
I'm using formsets and so far everything works well. However, in the clean_dr(self) method below I only want to validate that the DR field is empty if the form being check is not the first form in the formset. Ie if it's the first form in the formset then the DR field CAN be empty. Otherwise it cannot. Thank you forms.py class SplitPaymentLineItemForm(ModelForm): # Used to validate formset lineitems when creating or updating split payments ledger = GroupedModelChoiceField(queryset=Ledger.objects.filter((Q(coa_sub_group__type='e')|Q(coa_sub_group__type='a')),status=0).order_by('coa_sub_group__name', 'name'), choices_groupby = 'coa_sub_group', empty_label="Ledger", required=True) project = forms.ModelChoiceField(queryset=Project.objects.filter(status=0), empty_label="Project", required=False) class Meta: model = LineItem fields = ['description','project', 'ledger','dr',] # This init disallows empty formsets def __init__(self, *arg, **kwarg): super(SplitPaymentLineItemForm, self).__init__(*arg, **kwarg) self.empty_permitted = False def clean_dr(self): data = self.cleaned_data['dr'] if data != None: if data < 0: raise ValidationError('Amount cannot be negative') #if data == None: <---- I do not want this validation to apply to first item in formset # raise ValidationError('Amount cannot be empty') return data Views.py @login_required def split_payments_new(request): LineItemFormSet = formset_factory(SplitPaymentLineItemForm, formset=BaseSplitPaymentLineItemFormSet, extra=0, min_num=2) if request.method == 'POST': form = SplitPaymentForm(request.POST) lineitem_formset = LineItemFormSet(form.data['amount'], request.POST) if form.is_valid() and lineitem_formset.is_valid(): q0 = JournalEntry(user=request.user, date=form.cleaned_data['date'], type="SP") q1 = LineItem(journal_entry=q0, description=form.cleaned_data['store'], ledger=form.cleaned_data['account'], cr=form.cleaned_data['amount']) q0.save() q1.save() for lineitem in lineitem_formset: … -
How do I setup my own time zone in Django?
I live in Chittagong, Bangladesh and my time zone is GMT+6. How can i change to this time zone in Django settings? -
Concerning about https in development stage using django
I'm designing a web app using django as backend. I've read a couple of books and a lot of docs about it. They always refer to http protocol, at least for the development. But in the end it is recommenden to switch to https when it comes a production environment. I was wondering whether should I concern about https already in the development stage, or if it would be easier and faster to develop in basic http and switch to https right before production deployment. This previous question Rewrite HTTP to HTTPS Django suggest me (for what I've understood) that django app should speak simple http, and it should run behind a web server (e.g. nginx) which is responsible to accept https request from users and forward them via http to django. I hope some expert could enlighten me on that point. -
Is there a way to get the top most Transaction object during a nested atomic transaction in Django
I have a scenario where I want to perform some action on Transaction commit, but to user the tranasction.on_commit by django I need the transaction object. While the transaction get created a level above where I need it, is there a way I can get the transaction object inside the flow without explicitly passing it. -
Hepl with Django model
Could you help me? I'm writing the next code from django.db import models from warehouses.models import Warehouse, Location from products.models import Product from customers.models import Customer class Storage(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE, verbose_name="Cliente") warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE, verbose_name="Almacén") location = models.ForeignKey(Location, on_delete=models.CASCADE, verbose_name="Ubicación") product = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name="Producto") quantity = models.IntegerField(verbose_name='Cantidad') class Meta: verbose_name = "almacenamiento" verbose_name_plural = 'almacenamientos' ordering = ['product'] ## Ordenado por ... unique_together = (('customer', 'warehouse', 'location', 'product'),) def __str__(self): return self.product I know this is easy for a more experimented Django programmer. This is what i need: in Admin, for product, i need to choose products of the customer previously choosen, not all products; in that way, i need the same for location. i need to be able to choose only between de locations of de warehouse previously choosen. How could i do this? Thanks for your help... Gabriel -
Overriding __init__ method of Django Forms - when passing request.POST form has no data
I need to generate a random quiz from a database of Questions (entity in DB). I have overrided init method of the Form import django.forms as forms import random from .models import Question class ExaminationForm(forms.Form): # matricola = forms.CharField() def __init__(self, *args, **kwargs): super(ExaminationForm, self).__init__(*args, **kwargs) if not self.is_bound: questions = list(Question.objects.all()) random_questions = random.sample(questions, k=3) for i in range(len(random_questions)): field_name = random_questions[i].question_id answers = [(random_questions[i].answer_A,random_questions[i].answer_A), (random_questions[i].answer_B,random_questions[i].answer_B), (random_questions[i].answer_C,random_questions[i].answer_C), (random_questions[i].answer_D, random_questions[i].answer_D)] random.shuffle(answers) self.fields[field_name] = forms.ChoiceField(label=random_questions[i].title, choices=answers, widget=forms.RadioSelect) else: print('Forms should have data') The above code works and I can generate a Form with random questions but when i send the POST request to the server, the form is always without data This is the code in my view: if request.method == 'GET': form = ExaminationForm() context = { "has_done":False, "form":form } return render(request, 'examination.html', context) elif request.method == 'POST': form = ExaminationForm(request.POST) ### HERE THE FORM IS BLANK AND WITHOUT DATA if form.is_valid(): print('Form is valid') print(form.fields.values()) for field in list(form.cleaned_data): print(field) return HttpResponseRedirect('/') else: print('An error occurred') print(form.errors) return HttpResponseRedirect('/') -
Django token authentication test
I'm working on very simple API for creation and authentication user with a token. If I run a server and user is created manually then I can get a token, so it probably works as expected. But my unittest for creating token for user actually do not pass. My question is - why it actually do not pass? Probably I have missed something what is done by django underhood. Appreciate any feedback. Below you can see my serializer, view, model and a failing test. models class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): """Creates and saves a new user.""" if not email: raise ValueError('User must an email address') user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password=None): """Creates and saves a new superuser.""" user = self.create_user(email, password) user.is_admin = True user.is_superuser = True user.save() return user class User(AbstractBaseUser, PermissionsMixin): """Custom user model with email instead of username.""" email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' @property def is_staff(self): """Is the user a member staff?""" return self.is_admin serializer class AuthTokenSerializer(serializers.Serializer): """Serializer for the user authentication object""" email = serializers.CharField() password = serializers.CharField( style={'input_type': 'password'}, trim_whitespace=False ) def validate(self, … -
How to pass parameters from the form input box with action="get"?
I am trying to implement a form that sends a GET request but I want to pass arguments obtained by extracting data from the textfield. Here is an example: urls.py: urlpatterns = [ path('my-awesome-url/<str:foo>', MyAwesomeView.as_view(), name='my_awesome_url'), ] views.py: class ContactTracingView(View): def get(self, request, *args, **kwargs): foo = kwargs['foo'] context = {} # do some logic here return render(request, 'my_awesome_template.html', context) my_awesome_template.html: {% extends 'base.html' %} {% block content %} <form method="get" action="{% url 'my_awesome_url' foo %}"> <input type="text" name="foo"> <button type="submit" value="Submit">Submit</button> </form> {% endblock %} However, this code is not doing the job. I am receiving this error: NoReverseMatch Reverse for 'my_awesome_url' with no arguments not found. 1 pattern(s) tried: ['my\-awesome\-url\/(?P[^/]+)$'] I don't want to use POST, because I want the user to be able to bookmark the page. Also, when I tried to hardcode the url without writing parameters, csrf token was passed into the url, too. I want the url to be: my-awesome-website.tld/my-awesome-url/foo -
SyntaxError: Unexpected token < in JSON at position 0 while getting object
I am writing a SPA using DRF and Vue. I can get the list view class ArticleViewSet(viewsets.ModelViewSet): queryset = Article.objects.all() serializer_class = ArticleSerializer lookup_field = "slug" def perform_create(self, serializer): serializer.save(user=self.request.user) and my script export default { name: "Home", data() { return { articles:[] } }, methods: { getArticles() { let endpoint = 'api/articles/'; apiService(endpoint) .then(data=>{ this.articles.push(...data.results) }); } }, created() { this.getArticles(); console.log(this.articles) } }; when I try to route-link my articles : <router-link :to="{ name: 'article', params: { slug: article.slug }}" >{{article.content}} </router-link> I get error although I can see the object in the console. SyntaxError: Unexpected token < in JSON at position 0 vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in render: "TypeError: Cannot read property 'content' of undefined" this is my article.vue <template> <div class="single-question mt-2"> <div class="container"> {{article.content}} </div> </div> </template> <script> import { apiService } from "../common/api.service.js"; export default { name: "Article", props: { slug: { type:String, required: true } }, data(){ return { article: {} } }, methods: { getArticleData() { let endpoint = `api/articles/${this.slug}/`; apiService(endpoint) .then(data=> { this.article = data; }) } }, created() { this.getArticleData(); } }; </script> Can you help me to fix the error. Thanks -
Filter Django model on reverse relationship list
I have two Django models as follows: class Event(models.Model): name = models.CharField() class EventPerson(models.Model): event = models.ForeignKey('Event',on_delete='CASCADE',related_name='event_persons') person_name = models.CharField() If an Event exists in the database, it will have exactly two EventPerson objects that are related to it. What I want to do is to determine if there exists an Event with a given name AND that have a given set of two people (EventPersons) in that event. Is this possible to do in a single Django query? I know I could write python code like this to check, but I'm hoping for something more efficient: def event_exists(eventname,person1name,person2name): foundit=False for evt in Event.objects.filter(name=eventname): evtperson_names = [obj.person_name in evt.event_persons.all()] if len(evtperson_names) == 2 and person1name in evtperson_names and person2name in evtperson_names: foundit=True break return foundit Or would it be better to refactor the models so that Event has person1name and person2name as its own fields like this: class Event(models.Model): name = models.CharField() person1name = models.CharField() person2name = models.CharField() The problem with this is that there is no natural ordering for person1 and person2, ie if the persons are "Bob" and "Sally" then we could have person1name="Bob" and person2name="Sally" or we could have person1name="Sally" and person2name="Bob". Suggestions? -
Problems with session set_expiry method
I created a session for a view that some action, but i want to reset this session every week, i found set_expiry for that and tried to add that, but after working it reset all sessions in the website and i am doing logout. How to do that only for my action and not to touch all sessions in the website views.py def auth_join(request, room, uuid): room = get_object_or_404(Room, invite_url=uuid) join_key = f"joined_{room.invite_url}" if request.session.get(join_key, False): join_room(request,uuid) return HttpResponseRedirect(Room.get_absolute_url(room)) else: try: room_type = getattr(Room.objects.get(invite_url=uuid), 'room_type') except ValueError: raise Http404 if room_type == 'private': if request.method == 'POST': user = request.user.username form_auth = AuthRoomForm(request.POST) if form_auth.is_valid(): try: room_pass = getattr(Room.objects.get(invite_url=uuid), 'room_pass') except ValueError: raise Http404 password2 = form_auth.cleaned_data.get('password2') if room_pass != password2: messages.error(request, 'Doesn\'t match') return HttpResponseRedirect(request.get_full_path()) else: user = CustomUser.objects.get(username=user) try: room = get_object_or_404(Room, invite_url=uuid) except ValueError: raise Http404 assign_perm('pass_perm',user, room) if user.has_perm('pass_perm', room): request.session[join_key] = True request.session.set_expiry(10000) join_room(request,uuid) return HttpResponseRedirect(Room.get_absolute_url(room)) else: return HttpResponse('Problem issues') else: form_auth = AuthRoomForm() return render(request,'rooms/auth_join.html', {'form_auth':form_auth}) else: try: room = get_object_or_404(Room, invite_url=uuid) except ValueError: raise Http404 join_room(request,uuid) return HttpResponseRedirect(Room.get_absolute_url(room)) -
Django CreateView not saving item to model
My Django CreateView is not working. There are no bugs, but a new item is not being created when I submit the form. For example, when I go to the url and submit the form, a new item is not being added. Could you please help? You can also check out my GitHub repo for this project. Code for new_pattern.html {% extends 'patterns/base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">New Perler Pattern</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-success" type="submit">Add Pattern</button> </div> </form> </div> {% endblock %} Code for views.py from django.views.generic import (``` ListView, CreateView, ) from django.contrib.auth.mixins import LoginRequiredMixin from .models import Pattern class PatternListView(ListView): model = Pattern template_name = 'patterns/home.html' context_object_name = 'patterns' ordering = ['title'] class PatternCreateView(CreateView): model = Pattern fields = ['title', 'image'] template_name = 'patterns/new_pattern.html' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) Code for settings.py from . import views from django.urls import path urlpatterns = [ path('', views.PatternListView.as_view(), name='beadz-home'), path('new/', views.PatternCreateView.as_view(), name='new-pattern'), ] Code for models.py from django.db import models from django.contrib.auth.models import User class Pattern(models.Model): title = models.CharField(max_length=45) image = models.ImageField() author = models.ForeignKey(User, on_delete=models.CASCADE) def … -
does not appear to have any patterns in it. or circular import
recently i started to studying django but there is a problem into my code and i cant find what exactly could be a decent fix to this problem so i thought i would be good to ask. ... from django.urls import path from . import views ulrpatterns = [ path('' , views.index) ] ... well this is my code for urls.py into the articles directory. ... from django.contrib import admin from django.urls import path , include from home import views as home_views urlpatterns = [ path("" ,home_views.index ), path("about", home_views.about), path("Contact" ,home_views.contact ), path('admin/', admin.site.urls), path('articles/' , include('articles.urls')), ] ... this one is my main urls.py from what im seeing i called articles.urls but when im running my server it keeps givin me this error raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf '' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. -
IBM Cloud db2 django migrations python manage.py migrate
Created my first ibm db2 database on ibm cloud and connected it with django. With following settings: 'default':{ 'ENGINE' : 'ibm_db_django', 'NAME' : 'BLUDB', 'USER' : 'xxxxxxxxxxxxxxxx', 'PASSWORD' : 'xxxxxxxxxxxxxxxx', 'HOST' : 'dashdb-xxxxxxx-sbox-xxxxxxxxxx.services.eu-gb.bluemix.net', 'PORT' : '50000', 'PCONNECT' : True, } Connection works very well because I can run migrations for custom django app which I added. Even for session and content types. Problems arises due while running migrations for auth and admin. I get following error message: Exception('SQLNumResultCols failed: [IBM][CLI Driver][DB2/LINUXX8664] SQL0551N The statement failed because the authorization ID does not have the required authorization or privilege to perform the operation. Authorization ID: "XXXXXXXX". Operation: "SELECT". Object: "SYSIBMADM.ADMINTABINFO". SQLSTATE=42501 SQLCODE=-551' I understand that I dont have privileges to perform select operation on SYSIBMADM.ADMINTABINFO. My question is how can I give myself (admin account) privileges so that my python manage.py migrate does'nt throw an error. Or there is something wrong I am doing in django app itself. (INITIAL MIGRATIONS) -
sending email from django app doesnt work from server
I have an app that sends out an email when an object is create, this is the code for sending email: send_mail("New entryis added", "Hi a new entry is added", "myemail@gmail.com", [c.email for c in CustomUser.objects.all()], fail_silently=False) and this is my setting: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'myemail' EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = 587 EMAIL_USE_TLS = True I also made sure that my "Less secure app access" is on in google security setting. So with all thses I am able to send email with no issue in local server. However when I push the code to digital ocean droplet linux server, it throws some errors: SMTPAuthenticationError at /a/b/c/add/ (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbu\n5.7.14 VVGrAjSoYzu_W9fGpWsq5B3qMs04qWLzeqnxkFdrMaeVJumRRljQzXEyYpA9xt1MSYaii\n5.7.14 iyVCj2qaXbQzY5Tvc3mux9qViJSKE5yOozpCzao_qU0FhjYGX8IZ1xgd9PUep41I>\n5.7.14 Please log in via your web browser and then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 g9sm2079574pgj.89 - gsmtp') Exception Type: SMTPAuthenticationError I apreciate if someone can shed some light on what is the issue, Thanks, -
How to create asynchronous result submission based on table data using django-tables2
I am currently using django-tables2 to display some results to users. The results is coming from a RDF graph, so the results and number of columns may vary. I wrote the following code to deal with variable length of table columns: def createData(queryResults): if not queryResults: return (DummyTable,[]) else: myTableCol={} mylist = [] for i in queryResults: mydic = {} for j in i: className=str(type(j)).split(".")[1] mydic.update({className: j.name}) myTableCol.update({className: tables.Column()}) mylist.append(mydic) myTableCol.update({'Action': tables.TemplateColumn(template_name="secReqViews/radionbuttons.html", verbose_name=("Actions"), orderable=True)}) Meta = type('Meta', (object,), {'template_name':"django_tables2/bootstrap4.html", 'attrs':{"class": "paleblue"},}) myTableCol.update({'Meta':Meta}) QueryTable2=type('QueryTable', (tables.Table,), myTableCol) return QueryTable2, mylist Not to dwell on the algorithm, but you can see that I dynamically created the table columns using myTableCol={} and dynamically created class QueryTable2. I added a column call "Actions", which is my focus for this post. I would like to use this column to get information from the users asynchronously. So, for the results in the table, the user can select the "Yes" or "No" radio button to say whether the a row of results is correct or not. By selecting the "Yes" or "No" radio button, the information from the row will be sent and then save the row that is correct or not. Can this be done using Django-tables2? … -
Validation in case of multiple objects serializer
My data input is in the form of list of 'n' number of dicts "contact_person":[ { "contactperson_salutation[0]":"sddd", "contactperson_first_name[0]":"santoorr", "contactperson_last_name[0]":"", "contactperson_email[0]":"gfgh", "contactperson_mobile_number[0]":"", "contactperson_work_phone_number[0]":"jio" }, { "contactperson_salutation[1]":"dfsf", "contactperson_first_name[1]":"lux", "contactperson_last_name[1]":"", "contactperson_email[1]":"", "contactperson_mobile_number[1]":"", "contactperson_work_phone_number[1]":"9048" }, .............] My model is like this: class ContactPerson(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) contactperson_salutation = models.CharField(max_length=4, choices=SALUTATIONS) contactperson_first_name = models.CharField(max_length=128) contactperson_last_name = models.CharField(max_length=128, blank=True) contactperson_email = models.EmailField(blank=True, null=True) contactperson_mobile_number = models.CharField(max_length=20, blank=True) contactperson_work_phone_number = models.CharField(max_length=20, blank=True) How to write serializer when the fields names are changing for every dict in the input list.. And if errors occurs the Error Response should be in this format: [ { "contactperson_email[0]":"Invalid Email", "contactperson_mobile_number[0]":"Invalid mobile phone", "contactperson_work_phone_number[0]":"Invalid workphone number" }, { "contactperson_mobile_number[1]":"Invalid mobile phone", "contactperson_work_phone_number[1]":"Invalid workphone number" } ] -
declaring a global timer variable django
Good day, I have a django project up and running which has a users profile feature, users that register complete their profile with their personal information and other people on the site can view their profile. i have a field in my model for each user called profileVisits which counts each time a users profile is visited in the views.py. profileVisits = models.IntegerField(blank=True, null=True, default= 0) I want to use the profileVisits number to display the data in some kind of line graph which creates a average profileVisits graph. What i had in mind to approach this is to use a queue in python which has a max size of 5 integers q = Queue(maxsize = 5) this is because the data in q will be used in the data field for the chart.js. now the problem im facing is the use of a global variable in django. I want to add the data to q once a day with the number of profile visits and remove the oldest element in it, FIFO sequence, does anyone know how to initialize such a global timer variable in django or any better way to accomplish this -
how to do Django extract zip file after uploading
I am trying to upload a zip file and extract it into the static folder, bellow codeshare working file for uploading the zip file, how to extract the zip file to the static folder after uploading class Article(TimeStampModel): article_type = models.CharField( max_length=256, choices=ArticleTypeChoice.choices(), default=ArticleTypeChoice.ARTICLE.name) language = models.CharField(max_length=256, choices=LanguageChoice.choices()) title = models.CharField(max_length=1020) description = models.TextField(null=False, blank=True) article = models.FileField(null=False, blank=True, upload_to='static/') ``` -
DRF Custom Permission is not firing
I wrote a custom permission class for a drf project to protect my view: views.py class Employee(APIView): permission_classes = [BelongsToClient] serializer_class = EmployeeSerializer def get(self, request, pk, format=None): employee = EmployeeModel.objects.get(pk=pk) serializer = EmployeeSerializer(employee, many=False) return Response(serializer.data) def delete(self, request, pk, format=None): employee = EmployeeModel.objects.get(pk=pk) employee.Employees_deleted = True employee.save() return Response(status=status.HTTP_200_OK) My permission class: permission.py from rest_framework import permissions class BelongsToClient(permissions.BasePermission): message= "You are only authorized to view objects of your client" """ Object-level permission to only see objects of the authenticated users client """ def has_object_permission(self, request, view, obj): if obj.Mandant == request.user.Mandant: return True else: return False Unfortunatly this permission class isn't blocking my view even when it should. I dont know why. Did I miss something? -
how to compress django output with your own script?
I am new to Django and I know that it comes with many libraries that can compress the html, css and js files but i want to do this with my own script I have a python script which can compress these files and it works perfectly i want to use this script to compress my Django project output. I am using python 3.7.3 and django 3.0.5 -
Django: If I start a table, and then have a {% block %}{% endblock %} and close the table after, does it break the table?
I am making an html email template, and the header and footer for various email templates are on a single page that is included on each email. They are set up in tables, and the header and footer are contained in a single table. Because I am providing the body of the email in a separate file, it has to be broken up with a block. Apple mail renders the tfoot wrong, as if the footer is separate from the rest of the table. Is this because it is broken up by the block tags? How can I make it work, if so? This is the barebones setup for reference. <body> <table> <th> ---- </th> {% block body %} {% endblock %} <tfoot> <tr> <td> ----- </td> </tr> </tfoot> </table> </body> -
Operational Error: table "users_userscore" already exists
For my web app, I have two apps, one is morse_logs, the main app; second, is the users app, which mainly handles the users details and authentication, etc. At the moment in my users app, I have a UserProfile model, which only have one variable which is description, and now I am struggling to add one more variable score to user, so that each user will have one score variable to store their score, and the user's score will be updated after certain actions in morse_logs game1.html and morse_logs/views.py (the main app). I am really not familiar with modelling and create table, columns these sort of stuff... And when I do migrations, it gives me error like Operaional Error: table "users_userscore" already exists... I did try deleting the migrations py files... all my code are on github: https://github.com/phl6/morse_log So, my question is how can I update my model so I can have a score variable/field for each user which this variable can be updated in the morse_logs(main app). users/model.py from django.db import models from django import forms from django.contrib.auth.models import User from django.db.models.signals import post_save # Create your models here. class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) description = models.CharField(max_length=100, … -
Session Authentiction not working with django and vuejs
I am getting the csrf token and i am using axios to send a get request to the rest api. when i set the CSRF token and try to get the data, i get a 403 forbidden error. axios.get("my-api-url",{ header:{ 'X-CSRFTOKEN': csrftoken } }) .then(res -> console.log(res)) .catch(error => console.log(error))