Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using django's ORM to average over "timestamp without time zone" postgres field
I'm trying to average over a timestamp without time zone postgres field with django's excellent ORM like so: from django.db.models import Avg ModelName.objects.filter(a_field='some value').aggregate(Avg('time')) However I'm getting: function avg(timestamp without time zone) does not exist LINE 1: SELECT AVG("model_name"."time") AS "time__avg" FROM "m... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. Is there a way to do this with django's ORM?If not, how then do I workaround? -
Graphene mutation defined as null despiete returned value is NonNull
Im working with graphene to handle mutations on an application with django as backend. I wrote the following mutation: import graphene from django.db import transaction from graphql_jwt.decorators import login_required from app1.enums import SomeOptions from app1.models import SomeModel from app2.utils.some_api import SomeApi class SetOtherAppConfig(graphene.Mutation): url = graphene.NonNull(graphene.String) @login_required @transaction.atomic def mutate(self, info, *args, **kwargs): authorization_url = SomeApi().authorization_url user_id = int(info.context.session['_auth_user_id']) company_id = int(info.context.session['id_emp']) SomeModel.objects.get_or_create( company_id=company_id, code=SomeOptions.API.name, defaults={ 'name': SomeOptions.API.value, 'username': '', 'password': '', 'token': '', 'base_url': '', 'others': '', 'created_by_id': user_id, 'updated_by_id': user_id, }, ) return SetSomeConfig(url=authorization_url) The problem is that the mutation itself its being reported as null or string. The attribute url on the other hand can only be String as expected. How can I tell graphene that the mutation(or the class) can not be null? -
Seting Auth headers in Django tests
I am trying to write a test which goes through the signup/login workflow, and then attempts to change the status of a user, which requires them to be logged in. I verified that the first 2 POST requests work (the user is indeed created and then gets a valid auth token after logging in), however I cannot seem to pass in said token in the headers for the 3rd and final POST request. I also checked that the auth_headers variable is indeed set with the correct token, but I keep getting back a 401 status code. Thanks in advance! tests.py from email.headerregistry import ContentTypeHeader from urllib import request from wsgiref import headers from django.http import HttpRequest from django.test import TestCase, Client from rest_framework import status from rest_framework.test import APITestCase from django.urls import reverse from rest_framework.authtoken.models import Token from django.contrib.auth.models import User from profiles_api.serializers import UserProfileSerializer from django.contrib.auth import get_user_model from profiles_api.views import UserLoginApiView client = Client() User = get_user_model() class MyTestCase(APITestCase,UserLoginApiView): def test_add_status_to_profile(self): response = self.client.post("/api/profile/", data={ 'email':"John@gmail.com", 'name':'Pavle', 'password':'password' }) response = self.client.post("/api/login/", data={ 'username':"John@gmail.com", 'password':'password' }) auth_headers = { 'Authorization': 'Bearer ' + response.json()['token'] } response = self.client.post("/api/feed/", content_type='application/json', data={ 'status_text':'Hello world!' }, **auth_headers) self.assertEqual(response.status_code, status.HTTP_201_CREATED) -
Download multiple files with one link as zipped file django
I have a model with multiple files that when I get an object from it I want to be able to download all its related files from one click on anchor as a zip file -
After post or update request, I get 1062, "Duplicate entry '' for key 'crmapp_employees.email'". [Foreign key]
The concept is that I try to post or update a Case. The fields "title", "customer", "assigned_to" and "created_by" is required. Also the "assigned_to" and "created_by", are foreign keys of model Employees with email field as unique.I get the validation error for "title" if it's null but for the others I get the "Duplicate entry" error. The rest of the requests for Employees and Customers are working great.Thanks everybody in advance. Below you'll find the necessary code: -----------MODELS------------------------------ class Employees(models.Model): #auto increment id email = models.EmailField(unique=True) class Customers(models.Model): #auto increment id email = models.EmailField(unique=True, null=True, blank=True) class Cases(models.Model): #auto increment id title = models.CharField(max_length=100) assigned_to = models.ForeignKey( Employees, on_delete=models.PROTECT, related_name='assignee') created_by = models.ForeignKey( Employees, on_delete=models.PROTECT, related_name='creator') customer = models.ForeignKey( Customers, on_delete=models.PROTECT, related_name='cases',null=True, blank=True) -----------Serializers------------------------------ class SimpleEmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employees fields = ['id', 'full_name', ] read_only_fields=('full_name',) full_name = serializers.SerializerMethodField(method_name='get_full_name') def get_full_name(self, obj): return '{} {}'.format(obj.first_name, obj.last_name) class SimpleCustomerSerializer(serializers.ModelSerializer): class Meta: model = Customers fields = ['id', 'full_name',] read_only_fields=('full_name',) full_name = serializers.SerializerMethodField( method_name='get_full_name') def get_full_name(self, obj): return '{} {}'.format(obj.first_name, obj.last_name) class ViewUpdateCaseSerializer(WritableNestedModelSerializer, serializers.ModelSerializer): class Meta: model = Cases fields = ['id', 'category', 'title', 'description', 'customer', 'assigned_to', 'created_by', 'priority', 'status', 'creation_date', 'start_date', 'resolved_date', 'due_date', 'comments', 'cost', 'earning_fixed','earning_percent', 'clear_earning', 'price_without_vat','price_with_vat'] customer = … -
pip3 install cryptography MacOs gives error
the title says it all. This is my error message: ERROR: Command errored out with exit status 1: command: /Library/Developer/CommandLineTools/usr/bin/python3 /Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/site-packages/pip/_vendor/pep517/_in_process.py get_requires_for_build_wheel /var/folders/wy/9tlqy66d5630rd5htpz1dtnr0000gn/T/tmppjwpg3pg cwd: /private/var/folders/wy/9tlqy66d5630rd5htpz1dtnr0000gn/T/pip-install-cz6pcrd6/cryptography Complete output (52 lines): =============================DEBUG ASSISTANCE============================= If you are seeing a compilation error please try the following steps to successfully install cryptography: 1) Upgrade to the latest pip and try again. This will fix errors for most users. See: https://pip.pypa.io/en/stable/installing/#upgrading-pip 2) Read https://cryptography.io/en/latest/installation/ for specific instructions for your platform. 3) Check our frequently asked questions for more information: https://cryptography.io/en/latest/faq/ 4) Ensure you have a recent Rust toolchain installed: https://cryptography.io/en/latest/installation/#rust Python: 3.8.9 platform: macOS-12.0.1-x86_64-i386-64bit pip: 20.2.3 setuptools: 49.2.1 setuptools_rust: 1.3.0 =============================DEBUG ASSISTANCE============================= Traceback (most recent call last): File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/site-packages/pip/_vendor/pep517/_in_process.py", line 280, in <module> main() File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/site-packages/pip/_vendor/pep517/_in_process.py", line 263, in main json_out['return_val'] = hook(**hook_input['kwargs']) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/site-packages/pip/_vendor/pep517/_in_process.py", line 114, in get_requires_for_build_wheel return hook(config_settings) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/site-packages/setuptools/build_meta.py", line 146, in get_requires_for_build_wheel return self._get_build_requires( File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/site-packages/setuptools/build_meta.py", line 127, in _get_build_requires self.run_setup() File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/site-packages/setuptools/build_meta.py", line 142, in run_setup exec(compile(code, __file__, 'exec'), locals()) File "setup.py", line 39, in <module> setup( File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/site-packages/setuptools/__init__.py", line 165, in setup return distutils.core.setup(**attrs) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/site-packages/setuptools/_distutils/core.py", line 108, in setup _setup_distribution = dist = klass(attrs) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/site-packages/setuptools/dist.py", line 429, in __init__ _Distribution.__init__(self, { File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/site-packages/setuptools/_distutils/dist.py", line 293, in __init__ … -
Exceptions not bubbling up from LiveServerTestCase
We use LiveServerTestCase with Selenium for integration tests of a multi-page user flow. One of the flows is raising an exception at runtime, yet the test is passing. The exception is visible in the test logs, but does not cause the test to fail. Simplified example: class SmokeTest(LiveServerTestCase): def this_should_fail_but_passes(self): driver = webdriver.Chrome() driver.get('/home') # This test passes class HomeView(TemplateView): def get(self, request, *args, **kwargs): raise Exception("You would think the test would fail, but it doesn't.") Test passes, though exception is visible in logs... ... raise Exception("You would think the test would fail, but it doesn't.") Exception: You would think the test would fail, but it doesn't. . ---------------------------------------------------------------------- Ran 1 test in 2.248s OK The root cause seems to be that LiveServerTestCase launches a separate server instance and runtime errors that it experiences are logged, but do not bubble up as exceptions to the test client. -
Using multiprocessing with a dictionary that needs locked
I am trying to use Python's multiprocessing library to speed up some code I have. I have a dictionary whose values need to be updated based on the result of a loop. The current code looks like this: def get_topic_count(): topics_to_counts = {} for news in tqdm.tqdm(RawNews.objects.all().iterator()): for topic in Topic.objects.filter(is_active=True): if topic.name not in topics_to_counts.keys(): topics_to_counts[topic.name] = 0 if topic.name.lower() in news.content.lower(): topics_to_counts[topic.name] += 1 for key, value in topics_to_counts.items(): print(f"{key}: {value}") I believe the worker function should look like this: def get_topic_count_worker(news, topics_to_counts, lock): for topic in Topic.objects.filter(is_active=True): if topic.name not in topics_to_counts.keys(): lock.acquire() topics_to_counts[topic.name] = 0 lock.release() if topic.name.lower() in news.content.lower(): lock.acquire() topics_to_counts[topic.name] += 1 lock.release() However, I'm having some trouble writing the main function. Here's what I have so far but I don't know exactly how the arguments should be passed. def get_topic_count_master(): topics_to_counts = {} raw_news = RawNews.objects.all().iterator() lock = multiprocessing.Lock() with multiprocessing.Pool() as p: Any guidance here would be appreciated! -
Django ORM __in but instead of exact, contains case insensative?
I am currently trying to use the Django ORM to query the Recipe model's ingredients. class Recipe(models.Model): account = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True, blank=True) name = models.TextField(null=True, blank=True) class RecipeIngredients(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, null=True) ingredient = models.TextField(null=True, blank=True) What I have so far is ingredients = ["eggs", "bacon", "potato"] recipes = Recipe.objects.filter( recipeingredients__ingredient__in=ingredients ).alias( ningredient=Count('recipeingredients') ).filter( ningredient__gte=len(ingredients) ) From my understanding of this answer this will return all the items that contain only "eggs", "bacon", and "potato", but not say Eggs or Scrambled EGGS. Is there anyway to adjust this to have it search for all items that contains the ingredients and case insensative? -
Django: Avoid users uploading files, use their local storage instead?
So I have a Python script that extracts data from .ifc (3D models for the AEC Industry) files to a .csv or .xlsx and I would like to make it available in a web app. The files can get pretty big (> 400MB) and users are rarely owners of these files, so they are probably not allowed to upload them. So I am looking for a way to avoid the file upload. Is something like that possible with a Django App? Or should I look into creating a desktop app with some other framework? -
Radio button not saving selected option when refreshed (Django)
i have been having issues with my django ecommerce application one part of my application the user is meant to check a radio button the issue <input class="align-middle h-100" type="radio" name="deliveryOption" id="{{option.id}}" value="{{option.id}}"> my ajax $('input[type=radio][name=deliveryOption]:checked').on('change', function (e) { e.preventDefault(); $.ajax({ type: "POST", url: '{% url "checkout:cart_update_delivery" %}', data: { deliveryoption: $(this).val(), csrfmiddlewaretoken: "{{csrf_token}}", action: "post", }, success: function (json) { document.getElementById("total").innerHTML = json.total; document.getElementById("delivery_price").innerHTML = json.delivery_price; }, error: function (xhr, errmsg, err) {}, }); }); once i check the radio button, everything works fine but once i refresh the page, the selected radio button disappears but the radio button value is still stored in session. how do i fix it in such a way that even though i refresh the page, the selected radio button would still be selected. -
Can Djago create a database query that returns a dictionary of dictionaries?
Can Djago create a database query that returns a dictionary of dictionaries? The model contains a foreign key. Using these keys, I would like to have the query results sorted out. I would then like to provide these results using a rest framework. Illustration model: class Record(BaseModel): evse = models.ForeignKey( 'core.Evse', verbose_name=_('EVSE'), related_name='record_evse', on_delete=models.CASCADE, ) current_rms_p1 = models.FloatField( _('Current RMS P1'), default=0, validators=( MinValueValidator(0), MaxValueValidator((2**16 - 1) * 0.1), ) ) current_rms_p2 = models.FloatField( _('Current RMS P2'), default=0, validators=( MinValueValidator(0), MaxValueValidator((2**16 - 1) * 0.1), ) ) current_rms_p3 = models.FloatField( _('Current RMS P3'), default=0, validators=( MinValueValidator(0), MaxValueValidator((2**16 - 1) * 0.1), ) ) View: class RecordListAPIView(generics.ListAPIView): queryset = Record.objects.all() serializer_class = RecordSerializer def get_queryset(self): return Record.objects.all() How to edit a query to get this result? { "evse 1": [ { "current_rms_p1": 0.0, "current_rms_p2": 0.0, "current_rms_p3": 0.0 }, { "current_rms_p1": 0.0, "current_rms_p2": 0.0, "current_rms_p3": 0.0 } ], "evse 2": [ { "current_rms_p1": 0.0, "current_rms_p2": 0.0, "current_rms_p3": 0.0 } ] } Or this result: [ [ { "evse": 1, "current_rms_p1": 0.0, "current_rms_p2": 0.0, "current_rms_p3": 0.0 }, { "evse": 1, "current_rms_p1": 0.0, "current_rms_p2": 0.0, "current_rms_p3": 0.0 } ], [ { "evse": 2, "current_rms_p1": 0.0, "current_rms_p2": 0.0, "current_rms_p3": 0.0, } ] ] -
widgets for Category choice in Django
I just want add a class 'form control' in category choices class BlogForm(forms.ModelForm): # blog_title= forms.TextInput(label='Title',widget=forms.TextInput(attrs={'class':'form-control'})) # blog_content= forms.Textarea(label='Blog Content',widget=forms.Textarea(attrs={'class':'form-control'})) # blog_image= forms.ImageField(label='Blog Thambnail',widget=forms.ClearableFileInput(attrs={'class':'form-control'})) class Meta: model=Blog fields=['blog_title','category','blog_content','blog_image'] widgets={ 'blog_title':forms.TextInput(attrs={'class':'form-control'}), 'blog_content':forms.Textarea(attrs={'class':'form-control'}), 'category':forms.? 'blog_image':forms.ClearableFileInput(attrs={'class':'form-control'}), } is there any specific input field for that?i have given a question mark there. -
('28000', "[28000] [Microsoft][ODBC SQL Server Driver][SQL Server]Login failed for user 'hostname'
I have successfully deployed my django web application through Microsoft IIS FastCGI. So look wise my website seems to be fine. But after submitting the form on the website I am getting a database mssql error. So in the error, the username after the word USER is showing different from the username I have mentioned in views.py to establish a connection with the database. The username which is visible in the error is actually the hostname of the server on which I am deploying the web app (The sql server is in another server having another hostname). I am not able to figure out why the username is getting changed automatically and then giving an error. P.S - The web application is working fine without the deployment. Error views.py -
JSON local file retrieval with internationalization in django
I am making a website in django and have included internationalization. The internationalization works fine on other pages, except for when I am trying to retrieve a json file. The search takes in a word, then finds the corresponding JSON file in the javascript file (below). The search was working without issue until I added internationalization. Now I can see that when jquery goes to get the file, it includes the i18n abbreviation on the front, resulting in a 500 error. I have tried parsing the file location but the abbreviations are always added in getJSON. How do I fix this issue? The error specifically that shows in the console is: GET http://localhost:8000/en/static/assets/chowords/amo.json 500 (Internal Server Error) It makes sense that that is an error since the json file is actually at http://localhost:8000/static/assets/chowords/amo.json I tried storing the files in a directory "en" with static nested inside, but that did not resolve the issue. Code for reference: Javascript file new URLSearchParams(window.location.search).forEach((value,name)=>{ console.log(name) console.log(value) var fileword = value; var url = "./static/assets/chowords/" + fileword + ".json"; var xhr = new XMLHttpRequest(); xhr.open('HEAD', url, false); xhr.send(); console.log(xhr) document.getElementById("wordsearched").innerHTML =`<h1>${fileword} </h1>` if (xhr.status == "404") { //console.log("File doesn't exists"); let div = document.createElement('p') div.innerHTML … -
How to remove double quote from key value in dictionary
I have this payload: "cardType": "CHOICE", "step": 40, "title": {"en-GB": "YOUR REPORT"}, "description": {"en-GB": ""}, "options": [ {"optionId": 0, "text": {"en-GB": "Ask me"}}, {"optionId": 1, "text": {"en-GB": "Phone a nurse"}}, {"optionId": 2, "text": {"en-GB": "Download full report"}}, ], "_links": { "self": { "method": "GET", "href": "/assessments/898d915e-229f-48f2-9b98-cfd760ba8965", }, "report": { "method": "GET", "href": "/reports/17340f51604cb35bd2c6b7b9b16f3aec", }, }, } I then url encode it like so and redirect to a report view: url = reverse("my-reports") reverse_url = encodeurl(data, url) The urlencode output is returned as this: "/api/v2/ada/reports?cardType=CHOICE&step=40&title=" "%7B%27en-GB%27%3A+%27YOUR+REPORT%27%7D&description=" "%7B%27en-GB%27%3A+%27%27%7D&options=" "%5B%7B%27optionId%27%3A+0%2C+%27text%27%3A+%7B%27en-GB" "%27%3A+%27Ask+me%27%7D%7D%2C+%7B%27optionId%27%" "3A+1%2C+%27text%27%3A+%7B%27en-GB%27%3A+%27Phone+a+nurse" "%27%7D%7D%2C+%7B%27optionId%27%3A+2%2C+%27text%27%3A+%7B" "%27en-GB%27%3A+%27Download+full+report%27%7D%7D%5D&_links=" "%7B%27self%27%3A+%7B%27method%27%3A+%27GET%27%2C+%27href%27%" "3A+%27%2Fassessments%2F898d915e-229f-48f2-9b98-cfd760ba8965" "%27%7D%2C+%27report%27%3A+%7B%27method%27%3A+%27GET%27%" "2C+%27href%27%3A+%27%2Freports%2F" "17340f51604cb35bd2c6b7b9b16f3aec%27%7D%7D" In my report view I get the payload from the url query string: class Reports(generics.GenericAPIView): permission_classes = (permissions.AllowAny,) def get(self, request, *args, **kwargs): result = request.GET data = result.dict() print(data) Now the problem is that the output of the transferred data which is printed above has quotes for nested keys. { 'cardType': 'CHOICE', 'step': '40', 'title': "{'en-GB': 'YOUR REPORT'}", 'description': "{'en-GB': ''}", 'options': "[{'optionId': 0, 'text': {'en-GB': 'Ask me'}}, {'optionId': 1, 'text': {'en-GB': 'Phone a nurse'}}, {'optionId': 2, 'text': {'en-GB': 'Download full report'}}]", '_links': "{'self': {'method': 'GET', 'href': '/assessments/898d915e-229f-48f2-9b98-cfd760ba8965'}, 'report': {'method': 'GET', 'href': '/reports/17340f51604cb35bd2c6b7b9b16f3aec'}}" } Notice the double quote in the "description", "options" keys … -
Why empty response headers after ajax call?
I post to Django 4 from index.html ajax call function check() { $.ajax({ url: '{% url "cb" %}', type: 'POST', dataType: 'json', contentType: 'application/json', data: JSON.stringify({username: "{{request.user.username}}"}), headers: { 'X-Requested-With': 'XMLHttpRequest', 'X-CSRFToken': csrftoken, }, success: function (response) { if (response.balance == true) { message = 'OK' $('#customModal').attr('class', 'alert alert-success').html(message); // exit from func } else { message = 'Awaiting' $('#customModal').attr('class', 'alert alert-info').html(message); } }, error: function (response) { console.log(response); }, }); } $(document).ready(function(){ setInterval(check,60000); }); view.py def cb(request): print(request.headers) When ajax call from localhost , response headers is ok {'Content-Length': '32', 'Content-Type': 'application/json', 'Host': '127.0.0.1:8000', 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:100.0) Gecko/20100101 Firefox/100.0', 'Accept': 'application/json, text/javascript, */*; q=0.01', 'Accept-Language': 'en-US,en;q=0.5', 'Accept-Encoding': 'gzip, deflate, br', 'Referer': 'http://127.0.0.1:8000/payment', 'X-Requested-With': 'XMLHttpRequest', 'X-Csrftoken': 'wNCgxlQH0L2KhDxUkZ9uDE5zGdnbhejyynbmBEhhsU7J4HXfcmztxY69Zr9A3jbe', 'Origin': 'http://127.0.0.1:8000', 'Dnt': '1', 'Connection': 'keep-alive', 'Cookie': 'csrftoken=yeNnsws4zk4UBKo7qJe5GrP92Vz5Gh7wbcTqHHDNZtTjPEdlu31I6T3dXIKi3w8S; sessionid=u448kfdu0dovpgad2aj2ig0fuitgrj7o', 'Sec-Fetch-Dest': 'empty', 'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Site': 'same-origin'} When I open index.html from server public ip, the result of response print(request.headers) HostConnectionContent-LengthUser-AgentAcceptAccept-LanguageAccept-EncodingContent-TypeCookieCache-Control -
I am facing Multiple dictionary key value error in djnago
Csv_file=request.files[‘csv’] i am getting multiple dictionary key values error Csv_file = request.files.get(‘csv’) If i use this one I couldn’t able to file validation Name=csv_file.name Size=csv_file.size Here i am getting no attribute name and size -
How to set foreign key default field type?
I have simple model: id type is int(10) class Client(models.Model): name = models.CharField(max_length=45) surname = models.CharField(max_length=45) And second model with foreign key referencing Client table. from django.contrib.auth.models import User class ExtendedUser(models.Model): user = models.OneToOneField(User, on_delete=models.DO_NOTHING) client = models.ForeignKey('Client', on_delete=models.DO_NOTHING, blank=True, null=False, default=1) class Meta: managed = True db_table = 'extended_user' When I run python manage.py makemigrations and python manage.py migrate y have: 1215, 'Cannot add foreign key constraint' SHOW ENGINE INNODB STATUS; -> FOREIGN KEY (client_id) REFERENCES client(id): Cannot find an index in the referenced table where the referenced columns appear as the first columns, or column types in the table and the referenced table do not match for constraint. SQL sentence python .\manage.py sqlmigrate principal 0136: ALTER TABLE extended_user ADD COLUMN client_id bigint DEFAULT 1 NOT NULL , ADD CONSTRAINT extended_user_client_id_e51a6e7c_fk_client_id FOREIGN KEY (client_id) REFERENCES client(id); ALTER TABLE extended_user ALTER COLUMN client_id DROP DEFAULT; I tried client = models.ForeignKey('Client', on_delete=models.DO_NOTHING, blank=True, null=True, default=1) but still same error. Why Django is using bigint when I have primary key Int? How can I specify foreign key field type? -
Create or update related model object using Django management command
I need to periodically check on the status of a list of urls and report on their status. I created 2 models, one that has the list of main urls and another that holds all the sublinks on the pages of the main url. Model 1 class Site(CreationModificationDateBase, SoftDeletionModel): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=250, unique=True) category = models.ForeignKey(Category, on_delete=models.DO_NOTHING) url = models.URLField(unique=True) status_code = models.CharField(max_length=3, blank=True, default="") status_message = models.CharField(max_length=255, blank=True, default="") def __str__(self): return f'{self.name}' Model 2 class Link(CreationModificationDateBase, SoftDeletionModel): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) site = models.ForeignKey(Site, on_delete=models.DO_NOTHING, blank=True, null=True) url = models.CharField(blank=True, max_length=250, default="") status_code = models.CharField('Site Status', max_length=3, blank=True, default="") status_message = models.CharField(max_length=255, blank=True, default="") def __str__(self): return f'{self.url}' class Meta: ordering = ('url',) verbose_name = "link" verbose_name_plural = "links" I have this method on Model1 that returns the status code and message from the ListView on load. def get_links(self): data = requests.get(self.url).text soup = BeautifulSoup(data, features="html.parser") anchors = soup.find_all("a") links = [] links_status = [] for link in anchors: link_href = link.get("href") if f"https" in link_href: links.append(link_href) elif f"http" in link_href: links.append(link_href) elif f"/" in link_href and len(link_href) > 1 and self.url not in link_href: links.append(self.url + link_href) for ll in links: … -
Django Rest nested serializers multiple model CRUD operations using mixins
I'm trying to implement CRUD operation with nested serializer with multiple data models so that I can write all field at once when I call the API endpoint. Should I use some sort of filtering or for loop ? I've not found similar post that is using mixins Django-Rest nested serialization OneToOne Django rest framework- writable(create,update) double nested serializer models.py class Student(models.Model): student_id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) firstName = models.CharField(max_length=20) age = models.IntegerField(default=18) class Course(models.Model): student_id = models.ForeignKey(Student, on_delete=models.CASCADE) courseName = models.CharField(max_length=20) courseYear = models.IntegerField(default=2021) student = models.ManyToManyField(Student, related_name='courses') class Homework(models.Model): student_id = models.ForeignKey(Student, on_delete=models.CASCADE) hwName = models.CharField(max_length=20) hwPossScore = models.IntegerField(default=100) course = models.ForeignKey(Course, related_name='homeworks', on_delete=models.CASCADE, null=True, blank=True) students = models.ManyToManyField(Student) Serializers.py class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = "__all__" class HomeworkSerializer(serializers.ModelSerializer): class Meta: model = Homework fields = __all__ class CourseSerializer(serializers.ModelSerializer): class Meta: model = Course fields = "__all__" class All_Serializer(serializers.ModelSerializer): students = serializers.SerializerMethodField() homeworks = serializers.SerializerMethodField() courses = serializers.SerializerMethodField() def get_students(self, obj): students = obj.student_set.all() serializer = StudentSerializer(students, many=True) return serializer.data def get_homeworks(self, obj): homeworks = obj.homework_set.all() serializer = HomeworkSerializer(homeworks, many=True, read_only=True) return serializer.data def get_coruses(self, obj): courses = obj.courses_set.all() serializer = CourseSerializer(courses, many=True, read_only=True) return serializer.data class Meta: model = Student fields = ('student_id','firstName','age','homeworks','courses') … -
customizing django shell, injecting variables from a script
(likely was answered before, but no luck finding it) Every time I open a Django shell, I execute the same sequence of commands to get the environment set up, mostly loading JSON files which represent API responses, then doing data transformations to get the objects. Naturally, I started looking for a way to pre-initialize the environment with a script. I got as far as writing the script, which can be manually executed in a shell. However, a custom admin command doing all these things eludes me. Specifically, the line run_command('shell') starts a new process, which doesn't have any of the objects I've prepared in the script (as it ran in another process, duh). -
Django Keyerror on runserver until many restarts
I hope you can help me, I have a project with Django 2.2.25 and docker, but suddenly this error is showing: Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/local/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.8/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 387, in check all_issues = self._run_checks( File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "/usr/local/lib/python3.8/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/usr/local/lib/python3.8/site-packages/debug_toolbar/apps.py", line 37, in check_middleware if is_middleware_class(GZipMiddleware, middleware): File "/usr/local/lib/python3.8/site-packages/debug_toolbar/apps.py", line 81, in is_middleware_class middleware_cls = import_string(middleware_path) File "/usr/local/lib/python3.8/site-packages/django/utils/module_loading.py", line 17, in import_string module = import_module(module_path) File "/usr/local/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 843, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/app/shared/middleware.py", line 8, in <module> from shared.exceptions import JsonNotFound File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 682, in _load_unlocked KeyError: 'shared.exceptions' I believe … -
Drop down menu implementation
Im making a job searching website using django. I think a nice touch is to have a couple of options where when you press them a drop down menu comes down with more options. For example a salary option and when it is pressed you see a couple of different salaries and when one of them is pressed a new query is sent out to the database. Lets say we only want jobs that pay more than 50,000. What would a query like that look like -
How do I get django decouple to use my updated env vars?
I use DECOUPLE in my Django project and its awesome. However, I recently changed an env variable to a new key and after restarting the server, it still used the old env key. I used a print statement to see the key being used. Does it cache the old one and still use it ? If so, how do I clear it? My workaround for now is just to rename the key when i update the var. Any help would be greatly appreciated. Many thanks A.