Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to solve Django form attribute not working
All form attributes work fine, except on textarea. This is my code: # forms.py class VineyardForm(forms.ModelForm): class Meta: model = Vineyard fields = [ "name", "text", "wine_rg", "wines", "size", "grapes", "owner", "visits", "region", "regions", "cover" ] labels = { "name": "Vineyard or Property Name", "text": "Vineyard Description and Information", "wine_rg": "Wine Region and Country", } widgets = { "name": forms.TextInput(attrs={"placeholder": "Name of your vineyard..."}), "text": forms.Textarea(attrs={"placeholder": "something"}), "wine_rg": forms.TextInput(attrs={"placeholder": "Where is your vineyard located: region and country..."}), } When I look into the page inspector, I see this code: I think the problem is because I'm using ckeditor. Any suggestion? -
How to upload a file from an html into Django forms
Everytime I upload a file, forms.is_valid() = False. below is my views.py: def upload_pdf(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): # this is always FALSE!!! # write file into folder first text = handle_uploaded_file(request.FILES['file']) print("text") return HttpResponseRedirect('pdfExtractor_app/result.html') else: print("form not valid") form = UploadFileForm() return render(request, 'pdfExtractor_app/upload.html', {'form': form}) Here is my forms.py: from django import forms class UploadFileForm(forms.Form): title = forms.CharField(max_length=50) file = forms.FileField() Here is my upload.html file: <body> <form method="POST" class="post-form"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> </body> I input a title and a file, but I get the form never gets read in views.py. This is what's I get form.errors <ul class="errorlist"><li>file<ul class="errorlist"><li>This field is required.</li></ul></li></ul> [15/Dec/2021 21:10:56] "POST /upload_pdf/ HTTP/1.1" This is what's in the Querydict: <QueryDict: {'csrfmiddlewaretoken': ['b123ASDDoddfkkdzrPXa5P2kKEsp7dBASXQWXfffwwdffgKGLGVVffML'], 'title': ['as'], 'file': ['UsabilityTest.pdf']}> Thank you! -
ValueError at /register/ save() prohibited to prevent data loss due to unsaved related object 'user'
I am building a site in django but my registration is not working whenever i click submit i face this error i am setting up a profile for an user i am not sure this the right way so if there are better ways to do this plese do comment ValueError at /register/ save() prohibited to prevent data loss due to unsaved related object 'user'. Please Help , also i am a beginner a brief answer would be very much apperciated Here is the view : def register(request): profiles = UserProfilePage() forms = CreateUser() if request.method == 'POST': profiles = UserProfilePage(request.POST, request.FILES) forms = CreateUser(request.POST) if forms.is_valid() and profiles.is_valid(): user = forms.save() profile = profiles.save(commit=False) profile.user = user profile.save() group = Group.objects.get(name='user') user.groups.add(group) username = forms.cleaned_data.get('username') password = request.POST.get('password1') user = authenticate(request, username=username, password=password) login(request, user) messages.success(request, 'Account was successfully created for ' + username) return redirect('Login_Page') ctx = { 'forms': forms, 'profiles': profiles, } return render(request, 'Register.html', ctx) Forms: class CreateUser(UserCreationForm): class Meta(UserCreationForm.Meta): model = User fields = ['username', 'email', 'password1', 'password2'] help_texts = { 'username': 'This is your identification value so it must be unique' } def __init__(self, *args, **kwargs): super(CreateUser, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs['class'] = 'form-control' self.fields['email'].widget.attrs['class'] = … -
How to efficiently set order data for a parent object and its subs with recursion using python?
I used django for a model named Topics and the table data in the mysql database with default order value 1 like this: id has_sub_topic parent_id subject_module_level order 1 0 NULL 1 1 2 0 NULL 2 1 3 0 NULL 3 1 27 1 NULL 25 1 28 0 27 25 1 29 0 27 25 1 31 1 NULL 25 1 32 0 31 25 1 33 0 31 25 1 34 0 NULL 25 1 40 1 27 25 1 41 1 40 25 1 42 0 41 25 1 43 0 40 25 1 44 1 40 25 1 45 0 44 25 1 47 1 44 25 1 48 0 47 25 1 I want to set the order data based on its subject_module and its parent. So, the data in the table would be like this: id has_sub_topic parent_id subject_module_level order 1 0 NULL 1 1 2 0 NULL 2 1 3 0 NULL 3 1 27 1 NULL 25 1 28 0 27 25 1 29 0 27 25 2 31 1 NULL 25 2 32 0 31 25 1 33 0 31 25 2 34 0 NULL 25 3 40 1 27 … -
How to use choices in a model from a table previously populated with a fixture
I have the following model: class Countries(models.Model): region = models.CharField(max_length=250, null=False, blank=False) country = models.CharField(max_length=250, null=False, blank=False, unique=True) I populate the model via python manage.py loaddata db.json (JSON fixture) After the model is populated, I would like to use those regions and countries as 'options' for another model field class Project(models.Model): project_code = models.CharField(max_length=250, null=False, blank=False) status = models.CharField(#when creating a new project: default - active max_length=250, null=True, blank=True, default=PROJECT_STATUS_DEFAULT, choices=PROJECT_STATUS, ) region = models.CharField( max_length=250, null=False, blank=False, default=, #I would like to use here the options available in the Countries model choices=, #I would like to use here the options available in the Countries model ) country = models.CharField( max_length=250, null=False, blank=False, default=, #I would like to use here the options available in the Countries model choices= #I would like to use here the options available in the Countries model ) I did some research and it is clear to me how to use choices from a constants.py file, but I have not found a good explanation on how to use it with previous populated models. -
py manage.py runserver prints 'Python'
command 'py manage.py runserver', 'py -m manage.py runserver' just print 'Python' py --version Python 3.9.5 you can inspect manage.py file below Can you help me please? I watched related question and tried some of them, but still have had no progress -
Django nGix webserver no accepts api post Cron Job
there is web gui running and the function the function add_analyzer_recods() is executed by a cron job because its testing some ip stuff in development all works fine, de script is executed and the webpages templates are displaying data in production I have a nGix server and the templates aree displaying propers but as soon the crone job executes a test script the script fails : HTTPConnectionPool(host='127.0.0.1', port=8000): do: python manange.py runserver fixes the problem but that is not a permanent solution , any idea how nGix can handle post request calls? def add_analyzer_recods(self, response, job, _uuid_session): api = "api" response = requests.post("http://127.0.0.1:8000/" + api, json=self.ser(response, job, _uuid_session), headers=self.build_headers()) urls.py urlpatterns = [ path(r'^api$', ApiCallView.as_view()),] -
Django cannot resolve field when annotating
I have the following model: from django.db import models from tvproject_api.models import TVUser class Watched(models.Model): tvuser = models.ForeignKey(TVUser, on_delete=models.CASCADE, related_name='watched_tvuser') show_id = models.IntegerField() season_id = models.IntegerField() date_added = models.DateTimeField() class Meta: unique_together = [['tvuser', 'show_id', 'season_id']] I'm trying to annotate the TVUser model with a count of this by doing, TVUser.objects.filter().annotate(watched_count=Count('watched_tvuser')) But this gives me, django.core.exceptions.FieldError: Cannot resolve keyword 'watched_tvuser' into field. Weirdly, I have another model that looks almost exactly like the Watched model: from django.db import models from tvproject_api.models import TVUser class Watchlist(models.Model): tvuser = models.ForeignKey(TVUser, on_delete=models.CASCADE, related_name='watchlist_tvuser') show_id = models.IntegerField() season_id = models.IntegerField() date_added = models.DateTimeField() class Meta: unique_together = [['tvuser', 'show_id', 'season_id']] And this works totally fine: TVUser.objects.filter().annotate(watched_count=Count('watchlist_tvuser')) Not sure what the problem here is. I'm able to annotate lots of different fields, but the one for watched_tvuser is the only one not working. -
Page with a dynamic number of forms, each form for each table row
The company has workers performing various activities during a day. Each activity has start_time and finish_time. It is usual that workers forget to beep the end of activity (finish_time) and that's because there is a stored procedure read_unended time_from time_to which reads records between time_from and time_to which has not finish_time (is NULL). For example id name day start_time finish_time place activity 38 Thomas 2021-12-03 2021-12-03 08:51:38.000 NULL p1 a1 28 Charles 2021-12-02 2021-12-02 12:29:03.000 NULL p2 a2 49 John 2021-12-06 2021-12-06 11:59:48.000 NULL p3 a3 68 Jessie 2021-12-08 2021-12-08 10:55:12.000 NULL p4 a4 82 Susanne 2021-12-10 2021-12-10 12:38:03.000 NULL p5 a5 There is a form in (forms.py) class FromToForm(Form): start_date = DateField(widget=AdminDateWidget()) start_time = TimeField(widget=AdminTimeWidget()) end_date = DateField(widget=AdminDateWidget()) end_time = TimeField(widget=AdminTimeWidget()) There is a view in (views.py) which displays such a table. def ending(req): from_to_form = FromToForm() result = [] context = { 'form': from_to_form, 'result': result } if req.method == "POST": from_to_form = FromToForm(req.POST) if from_to_form.is_valid(): start = datetime.combine(from_to_form.cleaned_data['start_date'], from_to_form.cleaned_data['start_time']).isoformat() end = datetime.combine(from_to_form.cleaned_data['end_date'], from_to_form.cleaned_data['end_time']).isoformat() with connections["mssql_database"].cursor() as cursor: cursor.execute("EXEC read_unended @dt_od='%s', @dt_do='%s'" % (start, end)) result = cursor.fetchall() context['result'] = result return render(req, 'ending.html', context) else: return render(req, 'ending.html', context) else: return render(req, 'ending.html', context) and an associated … -
Django / Cloudrun / Docker migration failed
I try to create a Django project on Google Cloud Plateform (Cloudrun). I'm following the official tutorial here : https://codelabs.developers.google.com/codelabs/cloud-run-django#7 As I'm trying to execute my first basic migration : gcloud builds submit --config cloudmigrate.yaml \ --substitutions _REGION=$REGION I have this error : Step #2: ModuleNotFoundError: No module named 'app' Here's my project's tree : And my settings.py file : import io import os import environ import google.auth from google.cloud import secretmanager as sm # Import the original settings from each template from .basesettings import * try: from .local import * except ImportError: pass # Pull django-environ settings file, stored in Secret Manager SETTINGS_NAME = "application_settings" _, project = google.auth.default() client = sm.SecretManagerServiceClient() name = f"projects/{project}/secrets/{SETTINGS_NAME}/versions/latest" payload = client.access_secret_version(name=name).payload.data.decode("UTF-8") env = environ.Env() env.read_env(io.StringIO(payload)) # Setting this value from django-environ SECRET_KEY = env("SECRET_KEY") # Allow all hosts to access Django site ALLOWED_HOSTS = ["*"] # Default false. True allows default landing pages to be visible DEBUG = env("DEBUG") # Set this value from django-environ DATABASES = {"default": env.db()} INSTALLED_APPS += ["storages"] # for django-storages if "app" not in INSTALLED_APPS: INSTALLED_APPS += ["app"] # for custom data migration # Define static storage via django-storages[google] GS_BUCKET_NAME = env("GS_BUCKET_NAME") STATICFILES_DIRS = [] DEFAULT_FILE_STORAGE = … -
How to include an attribute of a foreign key in the Django Admin 'Add' page?
I have two following models: models.py: class Coordinates(models.Model): lat = models.DecimalField(max_digits=7, decimal_places=5, null=True) lng = models.DecimalField(max_digits=7, decimal_places=5, null=True) def __str__(self): return f"(lat: {self.lat}, lng:{self.lng})" class Event(models.Model): //other attributes note = models.CharField(max_length=100, blank=True) coordinates = models.ForeignKey(Coordinates, on_delete=models.CASCADE, related_name="event_coordinates") def __str__(self): return f"{self.type} by {self.creator}. {self.number_of_people}/{self.people_needed}." admin.py: from django.contrib import admin from .models import * admin.site.register(User) admin.site.register(Event) What I need to do to show 'lat' and 'lng' fields from cooridinates inside Admin Add page? -
Change _id from ObjectId to normal unique auto increment integer
I am pretty new to Django and web development so all of this is new to me as I am learning. I recently had a Django site setup and working with Postgresql. When I created it, I over complicated things and needed to use Postgresql specifcally because of one of the fields it had that SQLite did not have. Anyways, I am going to redo it (v2) and want to convert to a MongoDB. Right now I have everything set up but I noticed when I create new items from my models in the admin panel, it gets _id:ObjectId("61ba69238db76b91b4bf42f1") in the database. I am guessing this is the primary key? However, Django from my understanding is looking for a normal integer value. So when I am trying to remove things or modify things it gives me the error: Field 'id' expected a number but got 'None'. Should I be creating my own "id" field for each model? Should/can the default _id field be used? Thank you! -
QuerySet doesn't filter by user
So my code is written in Django backend and React frontend. For some reason, objects (in this case rats) aren't being filtered by the owner/user. I don't want to make permissions - anyone should be able to access someone else's rat, but in this specific list the user should only see the rats that belong to them. Running other filters work, such as birthday. But when I try filtering by user, no rats show up. There's also no error. What could be wrong? Object Serializer: class RatSerializer(FlexFieldsModelSerializer): user = serializers.CharField() body_colour = BodyColourSerializer() eye_colour = EyeColourSerializer() image = ImageSerializer() class Meta: model = rat Views: class ratViewset(FlexFieldsMixin): serializer_class = RatSerializer def get_queryset(self): userid = self.request.id return rat.objects.filter(user = userid) User serializer: class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) class Meta: model = User fields = ('id', 'username', 'password') And the JSON output for a user: { "id": 13, "username": "new" } In the JSON output for the object/rat, it clearly says which user it belongs to. So why won't the filter work? -
HMAC-SHA-256 signature verification failure on Telegram Web Login
I'm trying to add Telegram Web Login to my Django+Vue project. I'm handling login on Vue and directly passing the authorization data taken from TG to Django via DRF. That's working fine. The problem occurs in the verification on REST's POST view. When i was using js-sha256 library on Vue it works perfectly and im getting the true value of hash string provided by sha256.hmac() function from the js-sha256 library. I'm struggling to get same hash on Python. Here is the TG data verification explained and the code i'm using in POST view: class TelegramLoginSerializer(serializers.Serializer): raw_data = serializers.JSONField(required=True) def create(self, validated_data): raw_data = validated_data['raw_data'] tg_data = "\n".join([f'{k}={raw_data[k]}' for k in sorted(raw_data)]) if raw_data['hash'] != self.verify_telegram_data(tg_data): return PermissionDenied() else: ... @staticmethod def verify_telegram_data(data): secret_key = hashlib.sha256(settings.TG_BOT_TOKEN.encode('utf-8')) message = data.encode('utf-8') return hmac.new(secret_key.digest(), message, hashlib.sha256).hexdigest() -
Pagination with Django Class Based View on second page is messed up with formatting
I am trying to paginate the blog created in django using class based view, the first page is ok and well formatted but next pages won't retain the formatting and "div" "container" class overrides. this is the view.py: class HomeView(ListView): model = Post template_name = 'blog.html' paginate_by = 2 The template: <div class="container"> <h1 class="" style="margin-top: 4%;">The Blog</h1> {% for post in object_list %} <div class="row d-flex justify-content-center mb-5" style="margin-top: 5%;"> <div class="row "> <div class="col" style="margin-right: 0%; padding-right: 0%; padding-left: 0%;"> <img src = '{{ post.header_image.url }}' height="250" width="100%"> </div> <div class="row text-center"> <p class="title-two" style="padding-top: 15%;">{{ post.title }} </p> </div> </div> </div> <div class="pagination"> <span class="step-links"> {% if page_obj.has_previous %} <li><a href="?page=1">&laquo; first</a></li> <li><a href="?page={{ page_obj.previous_page_number }}">previous</a></li> {% endif %} <span class="current"> Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }} </span> {% if page_obj.has_next %} <li><a href="?page={{ page_obj.next_page_number }}">next</a></li> <li><a href="?page={{ page_obj.paginator.num_pages }}">last &raquo;</a></li> {% endif %} </span> </div> As shown in the pictures the first page works fine but next pages mess up with formatting. -
Trying to speed up a Serializer for a Django model - too many queries made
I'm trying to speed up my API. I need to (at least I assume I need to) use SerializerMethodField to calculate different bits of info I need included with the object. When I do that, in those methods I have to get the related _set data - which ends up hitting the database. As you can imagine, once I have a list of a large amount of users (for example: when I show all users in the web API) it takes forever to return, because of those hits to the DB. I'm not sure the best way to handle this - I believe prefetch_related and/or select_related is the answer, I'm just unsure of the best way to implement those functions. My code looks like this (pastebin version): # MODELS class User(models.Model): name = models.CharField(max_length=50) # ...etc... class Assignment(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.PROTECT ) job = models.ForeignKey(Job, on_delete=models.PROTECT) location = models.ForeignKey(Location, on_delete=models.PROTECT) # SERIALIZER class UserSerializer(serializers.HyperlinkedModelSerializer): assignment_job = serializers.SerializerMethodField() multiple_locations = serializers.SerializerMethodField() multiple_jobs = serializers.SerializerMethodField() class Meta: model = User fields = [ "url", "id", "username", "first_name", "last_name", "full_name", "email", "is_staff", "assignment_job", "multiple_locations", "multiple_jobs", ] def get_assignment_job(self, obj): assignment = obj.assignment_set.get(primary=True) return assignment.job.description def get_multiple_locations(self, obj): location_count = obj.assignment_set.filter( end_date__isnull=True … -
Django CreateView doesn't save object and doesn't give error
I'm working on a new project and I'm having difficulties adding new objects from the users page. It can be added from admin dashboard. This is the model: class Product(models.Model): title = models.CharField(max_length=150) price = models.IntegerField() image = models.ImageField(upload_to='products') description = models.TextField(max_length=500) owner = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('product-details', kwargs={'pk': self.pk}) I have this view: class ProductCreateView(LoginRequiredMixin, CreateView): model = Product fields = ['title', 'image', 'description', 'price'] def form_valid(self, form): form.instance.owner = self.request.user #form.save() return super().form_valid(form) product_form.html: {% extends "index/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">Product</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Save</button> </div> </form> </div> {% endblock content%} I tried a couple of times and I didn't work. So I searched for solutions and tried the following: instance = form.save(commit=False) instance.owner = self.request.user instance.save() return super().form_valid(instance) and this self.object.owner = self.request.user self.object = form.save() return super(ProductCreateView, self).form_valid(form) within the form_valid(). Neither of them worked. So I can open the form and fill the fields. When I send it, the object is not saved but it doesn't give any error. It just reloads the form. -
Is it possible read the document.body of a secondary window of different domain with postMessage()?
I am bulding a web app: a SPA using React in frontend and Django rest framework to API endpoints. I am in the part of the social login, which is done entirely in the backend (there is a exchange of providers tokens by own JWTs), so it is necessary make the request to the server, which redirect the user to the login of the specific provider. However, due to Facebook, Google and others providers do not permit this request using AJAX, I decided to create a popup (through window.open()) to make this redirection. Whether login is successful this window is redirect again towards a View of Django that returns a JSON with the JWT. Hence, this secondary window has a JWT in the domain of my server (Django). I planned read this JSON from the body of this secondary window to get the JWT, and I read (Code response form parent window, SecurityError: Blocked... and others) the only way to communicate windows in different domains is with postMessage(). But when I try, I receive the next message: SecurityError: Permission denied to access property "document" on cross-origin object In fact both of them are runnning in localhost, just with different port. … -
Django: What is wrong with this simple code to make user session validation. No errors in Visual Studio Code. Code in body section not work properly
I'm new here. Before asking the question, I tried to search. I have become convinced that it should work, and it is not. It works: <a href= "{% url 'logout' %}" class="btn btn-danger btn-sm">Logout</a> <a href= "{% url 'login' %}" class="btn btn-success btn-sm">Login</a> It is not: {% if user.is_autenticated %} <p>Hello {{ user.username }}</p> <a href= "{% url 'logout' %}" class="btn btn-danger btn-sm">Logout</a> {% else %} <a href= "{% url 'login' %}" class="btn btn-success btn-sm">Login</a> {% endif %} I am a beginner, so sorry experienced colleagues. :) Does anyone have an idea why? In the browser, you can always see only the login button, even after logging in. The login procedure works correctly because without logging in you cannot manipulate the data. Br Marek -
Django - querying and comparing multiple many to many relationships
Case: a user is creating a new requisition. I need to filter the fields(clearances) he is allowed to select/see in his requisition; based on a comparison of the following: users department(s) users workplace(s) compared against departments workplace(s) departments clearance fields clearance workplace(s) my models: class Place(models.Model): ... name = CICharField(max_length=100) descr = models.TextField(null=True, blank=True) parent = models.ForeignKey( 'self', on_delete=models.CASCADE, null=True,blank=True, related_name='children', ) #------------------------------ class User(AbstractUser): .... place = models.ManyToManyField(Place, blank=True, related_name='users') organization = models.ManyToManyField(Organization, blank=True) .... #------------------------------ class Organization(models.Model): ... parent = models.ForeignKey( 'self', on_delete=models.CASCADE, null=True,blank=True, related_name='children', ) place = models.ManyToManyField(Place, blank=True) ... #------------------------------ class Clearance(models.Model): ... parent = models.ForeignKey(Organization, on_delete=models.CASCADE, related_name='clearances') place = models.ManyToManyField('Place', blank=True, related_name='clearances') name = models.CharField(max_length=200) ... #------------------------------ class Requisition(models.Model): ... created_by = models.ForeignKey(User, on_delete=models.CASCADE) organization = models.ForeignKey(Organization, on_delete=models.CASCADE) place = models.ManyToManyField(Place, blank=False, related_name='requisitions') clearance = models.ManyToManyField(Clearance, blank=True, related_name='requisitions') ... Example scenario: user is a member of only 1 department: "Tech dpt" user is located in "London" and "Edinburgh" Tech dpt is located in "London", "Edinburgh" and "Glasgow" The clearances for "Tech dpt" is C1: London C2: Glasgow C3: London and Edinburgh C4: Edinburgh C5: London, Edinburgh and Glasgow the closest query I manage is the following: users_clearances = ( Clearance.objects #fetch all clearances attached to … -
How can I limit choices in this model form's ModelChoice widget using attributes in itself?
I can't find the way to limit the widget's choices to the objects in the fields 'jugadorA', and 'jugadorB', which are Jugador models. the form in forms.py: class ganadorForm(ModelForm): class Meta: model = Juego fields = ['ganador', 'jugadorA', 'jugadorB', 'torneo', 'ronda'] widgets = { 'ganador': ModelChoiceField(queryset=queryset=Jugador.objects.filter(Q(fields['jugadorA']) | Q(fields['jugadorB'])), to_field_name='nombre') } the model in models.py class Juego(models.Model): torneo = models.ForeignKey(Torneo, on_delete=models.CASCADE, null=False) ronda = models.ForeignKey(Ronda, on_delete=models.CASCADE, null=False) jugadorA = models.ForeignKey(Jugador, on_delete=models.SET_NULL, null=True, related_name='jugadorA') jugadorB = models.ForeignKey(Jugador, on_delete=models.SET_NULL, null=True, related_name='jugadorB') ganador = models.ForeignKey(Jugador, on_delete=models.SET_NULL, null=True, default=None, related_name='ganador') -
different classes for the same field rendered manually, each class is seen by different html files
Hello I have a question and it is that I want to place a class here {{form.status}} The problem is that {{form.status}} I am using it in a file called list.html and another called add.html. I already put the class from forms.py with widgets and I am using it in add.html file. I need another class for {{form.status}} that is only seen by the list.html file <div class="mb-3"> <label class="form-label mb-4" for="validationCustom14">Status</label> {{ form.status }} </div> -
Django models.foreignKey not being picked up and causing a Not Null Constraint error
Fairly new to Python and Django and having an issue with a foreignKey in that it's not being picked up. I am loading the data from some JSON I've get from an API call. There are two models I'm looking at, Team and Player. models (snipped for brevity): class Team(models.Model): code = models.IntegerField(null=True) name = models.CharField(max_length=30, null=True) short_name = models.CharField(max_length=3, null=True) id = models.IntegerField(primary_key=True) class Player(models.Model): total_points = models.IntegerField(null=True) squad_number = models.IntegerField(null=True) id = models.IntegerField(primary_key=True) goals_scored = models.IntegerField(null=True) minutes = models.IntegerField(null=True) team = models.IntegerField(null=True) team_code = models.IntegerField(null=True) player_team = models.ForeignKey(Team, on_delete=CASCADE) Both models have a unique id, id and code. Strange, but that's the way the data comes! Team.code maps to Player.team_code and Team.id maps to Player.team. In reality I could use either. I created player_team in Player with a ForeignKey link back to Team. I load and save Team first, then Player. teams = [Team(**data_dict) for data_dict in data['teams']] Team.objects.all().delete() Team.objects.bulk_create(teams) players = [Player(**data_dict) for data_dict in data['elements']] Player.objects.all().delete() Player.objects.bulk_create(players) The error I get is django.db.utils.IntegrityError: NOT NULL constraint failed: players_player.player_team_id I don't really understand how exactly it is linking the two models. I can see that in Player it is saying models.ForeignKey(Team...) so that makes sense. But how … -
Where can I find django(ORM) practice problems?
I'm really finding it very difficult to source practice problems for Django and its ORMs. I've heard Mosh's paid course has such exercises. I'm just getting started with Django mostly referring to youtube and its official documentation. I hope one of you who reads this could help me out. I don't know if this is the right forum to ask. Thanks in advance! -
Add CSRF to locust post request to prevent django error - Forbidden (CSRF cookie not set.)
How to add CSRF to the URL to test django from locust to prevent the error Forbidden (CSRF cookie not set.)? Here is what I have tried: @task def some_task(self): response = self.client.get("/") csrftoken = response.cookies['csrftoken'] self.client.post( "api/", {'csrfmiddlewaretoken': csrftoken}, headers={ 'X-CSRFToken': csrftoken, })