Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Integrate Bitpay Payment Gateway with Django?
Bitpay provides this button to add in the HTML file which also having a unique token key. Could anyone please help me in the process to integrate the Bitpay account through Django? I can't understand the further procedure. Thanks in advance. -
How to generate a dynamic html as string error f-string: expressions nested too deeply
I am requesting the html content of file by html_text = requests.get('https://buildpro.store/products/jaquar-water-closet-kus-wht-35951').text after getting this i want to extract the title price and a lot of different things and then fill my html template with the data and save it as text in csv file <html> <head> <title>Free Health Faucet On Jaquar Water Closet KUS-WHT-35951 </title> <script type="application/ld+json"> { "@context": "https://schema.org/", "@type": "Product", "name": "Health Faucet On Jaquar Water Closet", "image": [ "https://example.com/photos/1x1/photo.jpg", "https://example.com/photos/4x3/photo.jpg", "https://example.com/photos/16x9/photo.jpg" ], "description": "Get Jaquar Health Faucet Free (Worth Rs.999) On purchase of Jaquar Water Closet KUS-WHT-35951 and get 25% discount Product SKU : KUS-WHT-35951FREEALD-CHR-583 Closet Details: Product Code: KUS-WHT-35951 MRP: 15990 Closet Size: 385*595*385 Brand : Jaquar Closet Series: Kubix Type of Trap: P-Trap Type of Mounting", "sku": "0446310786", "mpn": "925872", "brand": { "@type": "Brand", "name": "Jaquar" }, "review": { "@type": "Review", "reviewRating": { "@type": "Rating", "ratingValue": "4", "bestRating": "5" }, "author": { "@type": "Person", "name": "BuildPro" } }, "aggregateRating": { "@type": "AggregateRating", "ratingValue": "4.9", "reviewCount": "989" }, "offers": { "@type": "Offer", "url": "https://buildpro.store/products/jaquar-water-closet-kus-wht-35951", "priceCurrency": "INR", "price": "1,119.99", "priceValidUntil": "2020-11-20", "itemCondition": "https://schema.org/UsedCondition", "availability": "https://schema.org/InStock" } } </script> </head> <body> </body> </html> The problem i face is that it have that i cant declare string by … -
AWS CloudFront combine static page from S3 and a dynamic page from a second server in same url
I have a static page on S3 which is served through AWS CloudFront. I now want to add a dynamic page form a server running Django under the same url. All pages served from the Django server have the url form '/subscription*'. Is it possible to use behavior settings in CloudFront to just add the Django app subscription to the url of CloudFront? -
Azure AD User access token requested by angular MSAL library and validation by WEB API using django_auth_adfs
I am playing to setup an Angular Single Page Application using MS MSAL Angular library to request an Access token to get user details from Microsoft Graph API and to authenticate into a custom WEB API build with DJango Python Framework. I use the django_auth_adfs and rest_framework libraries to build this API. I used the following tutorials to setup my environments : https://docs.microsoft.com/en-US/azure/active-directory/develop/tutorial-v2-angular-auth-code and https://azuread.github.io/microsoft-authentication-library-for-js/ref/msal-angular/ for the Angular Side https://django-auth-adfs.readthedocs.io/en/latest/rest_framework.html for the DJango side In my Angular App, I am able to login with my Azure AD credential. I can see that the access tokens for MS Graph and for my API are well fetched but this last is not accepted by my WEB API. On Azure AD, I setup the two applications. One for the Angular frontend and one for the django backend. Here are my configurations: For DJango backend: Authentication using Web configuration with redirect URI to http://localhost:8000/oauth2/callback and only organizational directory accounts (no implicit flow). Tried without and with a client secret (same result). No token configuration Permissions to MS Ggaph without admin consent required and granted for my organization as status. Scope defined to expose the API: api://xxxxxxxx-32d5-4175-9b05-xxxxxxxxxxxx/access_as_user (Admins and Users consent enabled) and my frontend … -
Efficiently get first and last model instances in Django Model with timestamp, by day
Suppose you have this model: from django import models from django.contrib.postgres.indexes import BrinIndex class MyModel(model.Models): device_id = models.IntegerField() timestamp = models.DateTimeField(auto_now_add=True) my_value = models.FloatField() class Meta: indexes = (BrinIndex(fields=['timestamp']),) There is a periodic process that creates an instance of this model every 2 minutes or so. This process is supposed to run for years, with multiple devices, so this table will contain a great number of records. My goal is, for each day when there are records, to get the first and last records in that day. So far, what I could come up with is this: from django.db.models import Min, Max results = [] device_id = 1 # Could be other device id, of course, but 1 for illustration's sake # This will get me a list of dictionaries that have first and last fields # with the desired timestamps, but not the field my_value for them. first_last = MyModel.objects.filter(device_id=device_id).values('timestamp__date')\ .annotate(first=Min('timestamp__date'),last=Max('timestamp__date')) # So now I have to iterate over that list to get the instances/values for f in first_last: first = f['first'] last = f['last'] first_value = MyModel.objects.get(device=device, timestmap=first).my_value last_value = MyModel.objects.get(device=device, timestamp=last).my_value results.append({ 'first': first, 'last': last, 'first_value': first_value, 'last_value': last_value, }) # Do something with results[] This … -
Access ForeignKey type from get_context_data
I have a CreateView in which i want to access the type(choice field) of foreign key in my model which is being used in my current model. Class Mymodel1(models.Model): name = models.CharField() type = models.CharField(choices=SomeTypes.choices()) Class MyModel2(models.Model): name = models.CharField() cas = models.ForeignKey(Mymodel1) Class Mymodel2CreateView(models.Model) def get_context_data(self): type = *queryset to access type from model1* -
can anyone help me to resolve MultiValueDictKeyError in django
I have added a drop-down in HTML for taking input, but I am getting an error MultiValueDictKeyError. Here I am sharing HTML code and Django code. <form method = "POST" style = "text-align:center;"> {% csrf_token %} {% comment %} <input type = "text" name = "consumer_id" placeholder = "Consumer Id" /> {% endcomment %} <fieldset style = "font-size:15px;"> <select name = "Consumer_ID"> <option value="0">Select </option> <option value="LT044T">LT044T</option> {% comment %} <option value="2P">2P</option> {% endcomment %} </select> </fieldset> <input type = "text" name = "fromdate" placeholder = "FROM: DD-MM-YYYY" /> <input type = "text" name = "todate" placeholder = "FROM: DD-MM-YYYY" /> <input type = "submit" value = "Search"/> </form> Here I am sending my view.py if request.method == 'POST': start_date = request.POST['fromdate'] print(start_date) end_date = request.POST['todate'] print(end_date) consumer_id = request.POST['consumer_id'] print(consumer_id) else: start_date = "01-05-2022" end_date = "04-05-2022" consumer_id = "hello" -
Django - Display child elements based on parent in ModelChoiceField queryset
I have created models that each of them based on own parent. On forms I have used ModelChoiceField. When the user selects the element from Category choice field, on Subcategory field should be displayed only its child elements. And also after selecting the Subcategory, on ProductCategory choice field should be displayed child elements. it should have been something like this But I am getting error: TypeError: Field 'id' expected a number but got <django.forms.models.ModelChoiceField object at 0x7f3d1f9f0ac0>. How can I improve it? models.py: class Category(models.Model): name = models.CharField("Category Name", max_length=100, unique=True) link = models.CharField("Category Link", max_length=250) def __str__(self): return self.name class Subcategory(models.Model): parent = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) name = models.CharField("Sub-category Name", max_length=100, unique=True) link = models.CharField("Sub-category Link", max_length=250) def __str__(self): return self.name class ProductCategory(models.Model): parent = models.ForeignKey(Subcategory, on_delete=models.CASCADE, null=True) name = models.CharField("Product-Category Name", max_length=100, unique=True) link = models.CharField("Product-Category Link", max_length=250) def __str__(self): return self.name class ProductSubCategory(models.Model): parent = models.ForeignKey(ProductCategory, on_delete=models.CASCADE, null=True) name = models.CharField("Product-Sub-Category Name", max_length=100, unique=True) link = models.CharField("Product-Sub-Category Name", max_length=250) def __str__(self): return self.name forms.py class CategoryForm(forms.Form): category = forms.ModelChoiceField(queryset=Category.objects.all()) subcategory = forms.ModelChoiceField(queryset=Subcategory.objects.filter(parent=category)) prodcategory = forms.ModelChoiceField(queryset=ProductCategory.objects.filter(parent=subcategory)) On views.py I am just running external script def homepage(request): context = {} form = CategoryForm() context['form'] = form if request.GET: temp … -
In django how to generate dynamic url after domain name for every page?
I am building a blog website where I set a unique title for every article. I want the article should have url domain_name/<article_title>/. Suppose I have model A : class A(models.Model): title = models.CharField(max_length=500,unique=True) app.urls.py file : urlpatterns = [ path('',view.index,name="index"), path('contact/', contact, name="contact"), path('about/', about, name="about"), path('terms-and-conditions/', terms, name="terms_and_conditions"), path('privacy/', privacy, name="privacy"), path('<str:title>/', article_details, name="article_details"), ] I have view file as follows: def article_details(request,title): try: article = A.objects.get(title=title) context = {'article':article} return render(request,"app/article.html",context=context) except: return render(request,"app/404.html") project.urls file: urlpatterns = [ path('admin/', admin.site.urls), path('', include('app.urls', namespace='clothes')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) handler404 = 'clothes.views.view_404' My question is: Is this type of page rendering good or not? Does 404 request handles correctly? -
Django ModuleNotFoundError: No module named while importing from a folder
I'm trying to run a command that is supposed to import the models from an upper folder I'm trying to run crate_university.py which is on the assessments/university/commands directory This should be importing from the models which is located at assessments/university/ folder I have the following code: from django.core.management.base import BaseCommand from university.models import University, TeacherDegree, Teacher Buen when I try to run the command I get the following error: -
Why do you need "import gettext_lazy as _" in this Django code?
I want to add a new field to my Django models.py from django.core.validators import RegexValidator from django.db import models class MyModel(models.Model): postal_code = models.CharField( max_length=6, validators=[RegexValidator('^[0-9]{6}$', _('Invalid postal code'))], ) This code gave me an error NameError: name '_' is not defined. After some googling, I found a solution but don't understand the solution. To fix this problem, I added the line from django.utils.text import gettext_lazy as _ Now, the code becomes like this; from django.core.validators import RegexValidator from django.db import models from django.utils.text import gettext_lazy as _ class MyModel(models.Model): postal_code = models.CharField( max_length=6, validators=[RegexValidator('^[0-9]{6}$', _('Invalid postal code'))], ) What is the purpose of from django.utils.text import gettext_lazy as _ ? Why does it fix the error? I am using Django v4 -
Object of type date is not JSON serializable, getting error in django templates
I am trying to dumps data to json in views.py. And send to django templates for javascript but getting error. models.py class resource(models.Model): title=models.CharField(max_length=100) size=models.CharField( max_length=20, default="") desc=models.TextField(default="") file=models.FileField(default="", blank=True) url= models.URLField(max_length=200, blank=True) varient=models.CharField(max_length=100, default="") Brand = models.ForeignKey(brand,on_delete=models.CASCADE, default="") Model = models.ForeignKey(model,on_delete=models.CASCADE, default="") Categories = models.ForeignKey(category,on_delete=models.CASCADE, default="") update_at=models.DateField(auto_now=True) paymentvarified=models.BooleanField(default=False) slug=models.SlugField(default="", unique=True, blank=True) Tags = TaggableManager(blank=True) views.py data={ 'limitjsondata':json.dumps(list(resource.objects.values())), 'get_pro':get_pro, 'Resource':Resource, 'pro_member':pro_members, } return render(request, 'firmApp/download.html', data) When I run server and go to specic page it through an error. Object of type date is not JSON serializable -
in Django basehttp.py getting ImproperlyConfigured on app_path = apollo.wsgi.application
When I run python manage.py check I get no errors. However when I try to runserver I get... File "C:\Users\oliver\apollodev\django-apollo-forms\venv\lib\site-packages\django\core\servers\basehttp.py", line 50, in get_internal_wsgi_application raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: WSGI application 'apollo.wsgi.application' could not be loaded; Error importing module. The offending code block is... try: print("/////////////////////////basehttp.py app_path = ", app_path ) return import_string(app_path) except ImportError as err: raise ImproperlyConfigured( "WSGI application '%s' could not be loaded; " "Error importing module." % app_path ) from err I added the Print() to see what is going on and get... Quit the server with CTRL-BREAK. /////////////////////////basehttp.py app_path = apollo.wsgi.application Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\oliver\apollodev\django-apollo-forms\venv\lib\site-packages\django\core\servers\basehttp.py", line 48, in get_internal_wsgi_application return import_string(app_path) I tried adding apollo.wsgi.application to INSTALLED_APPS but got a new error... File "C:\Users\oliver\apollodev\django-apollo-forms\venv\lib\site-packages\django\apps\registry.py", line 83, in populate raise RuntimeError("populate() isn't reentrant") At a loss on what to try next. -
The problem with adding data to Many To Many Django
I want to add data to Many To Many. The api_data variable receives data from the API. I'm starting to process them. Instead of set, I also tried add. Nothing helps. I don't know what's wrong def write_add_serv_to_stations() -> None: stations_arr = [] for data in api_data: additional_ids = data['serviceIds'].split(',') if data['serviceIds'] else [85] for additional_id in additional_ids services = Services.objects.filter(id=1) additional = Additional.objects.filter(id__in=[additional_id]) station = Stations.objects.filter(station_id=data['id']) stations = Stations(service=station.service.set(services), additional=station.additional.set(additional)) stations_arr.append(stations) Stations.objects.bulk_update(stations_arr) An error comes out Traceback (most recent call last): File "C:\Users\Ramil\AppData\Local\Programs\Python\Python310\lib\code.py", line 90, in runcode exec(code, self.locals) File "<input>", line 1, in <module> File "D:\Work\Django_work\Locator\projects\locator\parsing.py", line 88, in write_add_serv_to_stations stations = Stations(service=station.service.set(services), File "D:\Work\Django_work\Locator\projects\venv\lib\site-packages\django\db\models\base.py", line 582, in __init__ _setattr(self, prop, value) File "D:\Work\Django_work\Locator\projects\venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 606, in __set__ raise TypeError( TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use service.set() instead. I've sorted through everything that is possible and impossible, I can't understand what the error is. Here are the models class Services(models.Model): id = models.PositiveIntegerField(primary_key=True, verbose_name='id') name = models.CharField(max_length=50, verbose_name="Название") class Meta: verbose_name_plural = "Типы топлива" class Additional(models.Model): id = models.PositiveIntegerField(primary_key=True) name = models.CharField(max_length=100, verbose_name='Дополнительные услуги') class Stations(models.Model): service = models.ManyToManyField(Services, verbose_name='Название топлива', null=True, blank=True) additional = models.ManyToManyField(Additional, verbose_name='Услуги', null=True, blank=True) Please … -
Django Filtering of Data to get Top Athlete for Each Event
OK, I am at my wits end on this query. I would like to build a query that returns the top performance in each event (separated by men and women). Here is my model structure: class Athlete(models.Model): Graduation = models.IntegerField() Athlete = models.CharField(max_length=200, null=True) Male = models.BooleanField() Active = models.BooleanField() First = models.CharField(max_length=200, blank=True) Last = models.CharField(max_length=200, blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.Athlete class Meet(models.Model): MeetName = models.TextField() State = models.BooleanField() Indoor = models.BooleanField() Location = models.CharField(max_length=200, null=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.MeetName class Event(models.Model): EventName = models.CharField(max_length=200, null=True) FieldEvent = models.BooleanField() Current = models.BooleanField() Relay = models.BooleanField() Order = models.IntegerField() MeasurementSystem = models.CharField(max_length=20) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.EventName class Performance(models.Model): EventID = models.ForeignKey(Event, on_delete=models.SET_NULL,null=True) Mark = models.CharField(max_length=200, null=True) MarkRawLarge = models.IntegerField() MarkRawSmall = models.DecimalField(decimal_places=3,max_digits=20) MeetID = models.ForeignKey(Meet, on_delete=models.SET_NULL,null=True) PerformanceNote = models.CharField(max_length=10,null=True,blank=True) CY = models.IntegerField(null=True) EventDate = models.DateField(null=True) Notes = models.TextField(null = True,blank=True) Archive = models.BooleanField() StateChamp = models.BooleanField(null=True) AthleteID = models.ManyToManyField(Athlete) Confirmed = models.BooleanField(null=False,default=False) Locked = models.BooleanField(null=False,default=False) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) I have 4 queries that successfully produce the top ten athletes in a particular category as shown here (code excerpt from … -
How to compare a datetime to datetimes stored in a model?
I have a model as follows that includes version_date, which is a DateTimeField: class Flow(models.Model): name = models.CharField(max_length=30, choices=FLOW_NAMES) version = models.PositiveSmallIntegerField() version_date = models.DateTimeField() file = models.FileField(blank=True,null=True) last_accessed = models.DateTimeField(auto_now=True) I would like to compare a timestamp which I have extracted from a XML file, to each version_date value stored in the model. How can I iterate through the model comparing the extracted timestamp to each version_date in the model? -
Filter one date from DateTimeTZRange
I have a model which returns the date range in below mentioned way i need to check if today is 10 days before the days as you can see in the below returned date if today date + 10 days = start_end_range class MyModel(models.Model): start_end_range = ranges.DateTimeTZRange() 'start_end_range': DateTimeTZRange(datetime.datetime(2022, 11, 30, 20, 0), datetime.datetime(2022, 11, 30, 20, 30), -
How to get the value of selected checkboxes from HTML into my Django Views?
Working for the first time on HTML and Djnago. I wrote a custom HTML excluded_leagues.html <h1>Excluded Leagues</h1> <div class="excluded_leagues"> <form action="/superprofile/save_excluded_leagues/" method="POST">{% csrf_token %} <table id="excluded_leagues_list"> <thread> <tr> <th scope="col"> <div class="text"> <span>Excluded</span> </div> </th> <th scope="col"> <div class="text"> <span>League ID</span> </div> </th> <th scope="col"> <div class="text"> <span>League Name</span> </div> </th> <th scope="col"> <div class="text"> <span>Sport</span> </div> </th> </tr> </thread> <tbody> {% for league in object_list %} {% if league.status == 'Active' %} <tr> <td><input type="checkbox" value="{{ league.id }}" name="selected_league"></td> <td>{{ league.id }}</td> <td>{{ league.name }}</td> <td>{{ league.sport }}</td> </tr> {% else %} {% endif %} {% endfor %} </tbody> </table> <div> <button type="submit" name="apply">Save changes</button> </div> </div> <ul> I am trying to grab the league.id of all the selected checkboxes and use them in my views views.py def save_excluded_leagues(request): if 'apply' in request.POST: league_id_selected = request.POST.getlist('selected_league') return HttpResponse("Hello") I need to grab the values league.id of all the selected checkboxes, but I am unable to grab the value in my views.py file. -
django create custom id def save()
I have this postgres function, What it does is when I save an item, it creates an cl_itemid test2021-20221-1. then in table clearing_office the column office_serial increments +1 so next item saved will be test2021-20221-2 SELECT CONCAT(f_office_id,f_sy,f_sem,'-',office_serial) INTO office_lastnumber from curriculum.clearing_office where office_id=f_office_id; UPDATE curriculum.clearing_office SET office_serial =office_serial+1 where office_id=f_office_id; { "studid": "4321-4321", "office": "test", "sem": "1", "sy": "2021-2022", } Is it possible to create this thru django models or perhaps maybe an alternative solution for this problem class Item(models.Model): cl_itemid = models.CharField(primary_key=True, max_length=20) studid = models.CharField(max_length=9, blank=True, null=True) office = models.ForeignKey('ClearingOffice', models.DO_NOTHING, blank=True, null=True) sem = models.CharField(max_length=1, blank=True, null=True) sy = models.CharField(max_length=9, blank=True, null=True) class Meta: managed = False db_table = 'item' -
define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings
I originally installed Python 3.10.4 on my windows 11 OS. I then installed virtualenv, via pip, ran the virutalenv worked fine. I then Installed Django with the env open. I tried... Restarted my computer and got this error when I try to run django-admin runserver in env. I've also installed it in Ubuntu 22.04.1 LTS, I get the same error. I opened the manage.py and changed ('DJANGO_SETTINGS_MODULE', 'mysite.settings') Error ImproperlyConfigured: You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'real_virgin.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() -
Problem with ImageForm. cant save it to server Django
IntegrityError at /profile/ (1062, "Duplicate entry '1' for key 'catalog_profile.user_id'") The image is saved to the server (giving an error along the way), but is not written to the database, before that error i had problem with user_id in tho.save() what i must to change ? models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save, pre_save from django.dispatch import receiver class Clan(models.Model): clan_name = models.CharField(max_length=40) clan_tag = models.CharField(max_length=5) clan_exp = models.IntegerField(default=0) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) kills = models.IntegerField(default=0) exp = models.IntegerField(default=0) tokens = models.IntegerField(default=0) coins = models.IntegerField(default=0) chanks = models.IntegerField(default=0) privilege = models.CharField(max_length=15) clan = models.ForeignKey(Clan, blank=True, null=True, on_delete=models.SET_NULL) skin = models.ImageField(default='default.png', null=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() forms.py from django import forms from.models import Profile, User class SkinForm(forms.ModelForm): class Meta: model = Profile fields = ('skin',) labels = {'skin': '',} #exclude = ('user',) widgets = { 'skin': forms.FileInput(attrs={'class': 'file_input', 'placeholder': ''}), } views.py (where i have problem) tho.save give me an error def profile(request): if request.method == "POST": form = SkinForm(request.POST, request.FILES) u = request.FILES['skin'] if form.is_valid(): tho = form.save(commit=False) tho.user = request.user.profile.user tho.save() return render(request, 'profile.html', context={'skin': skin, 'form': SkinForm}) … -
websocket.send method not doing anything in javascript even if the connection established successfully
guys, I had to implement WebSockets using channels in Django,but even after the connection is established successfully, WebSocket.send method is not working in javascript and it works only inside websocket.onopen here's my javascript code for the socket let noteSocket = null function connect(){ noteSocket = new WebSocket('ws://' + window.location.host + `/ws/mycourses/{{ course.productId }}/chapters/{{ last_followed.chapter.chapterId }}/lessons/{{ last_followed.lessonId }}/notes/`) noteSocket.onopen = function(e) { console.log("Successfully connected to the WebSocket."); } noteSocket.onclose = function(e) { console.log("WebSocket connection closed unexpectedly. Trying to reconnect in 2s..."); setTimeout(function() { console.log("Reconnecting..."); connect(); }, 2000); }; noteSocket.onmessage = function(e){ const data = JSON.stringify(e.data) renderNote(data.note, data.timestamp) } } after executing the connect function I get these in the Django development server terminal WebSocket CONNECT /ws/mycourses/879521fa-75f9-4c95-8b61-039f7503ecae/chapters/91a12b16-35f7-4702-a002-35b228010a94/lessons/90a125ad-570e-437e-ac67-46cdeb55a068/notes/ [127.0.0.1:53424] and I get from my browser console: Successfully connected to the WebSocket. I am using google chrome, and my os is arch Linux(note: I even tried in firefox but it didn't work) -
Why Django does not recognize my USERNAME_FIELD in User Model
I have this error when I try to make migrations "django.core.exceptions.FieldDoesNotExist: User has no field named 'username'" This is the complete error log here below: Traceback (most recent call last): File "C:\Users\acer\Desktop\dev\python\entornos\djusers\lib\site-packages\django\db\models\options.py", line 668, in get_field return self.fields_map[field_name] KeyError: 'username' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\acer\Desktop\dev\python\djusers\djusers\manage.py", line 22, in <module> main() File "C:\Users\acer\Desktop\dev\python\djusers\djusers\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\acer\Desktop\dev\python\entornos\djusers\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\acer\Desktop\dev\python\entornos\djusers\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\acer\Desktop\dev\python\entornos\djusers\lib\site-packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\acer\Desktop\dev\python\entornos\djusers\lib\site-packages\django\core\management\base.py", line 443, in execute self.check() File "C:\Users\acer\Desktop\dev\python\entornos\djusers\lib\site-packages\django\core\management\base.py", line 475, in check all_issues = checks.run_checks( File "C:\Users\acer\Desktop\dev\python\entornos\djusers\lib\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\acer\Desktop\dev\python\entornos\djusers\lib\site-packages\django\contrib\auth\checks.py", line 55, in check_user_model if not cls._meta.get_field(cls.USERNAME_FIELD).unique and not any( File "C:\Users\acer\Desktop\dev\python\entornos\djusers\lib\site-packages\django\db\models\options.py", line 670, in get_field raise FieldDoesNotExist( django.core.exceptions.FieldDoesNotExist: User has no field named 'username' This is my models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin # Create your models here. class User(AbstractBaseUser, PermissionsMixin): """ clase para generar mi modelo personalizado de Users """ GENDER_CHOICES = [ ('1', 'hombre'), ('2', 'mujer') ] username = models.CharField("nombre de usuario", max_length=50, unique=True), full_name = models.CharField("nombre completo", max_length=150), gender = models.CharField("género", max_length=1, choices=GENDER_CHOICES), age … -
DJANGO - 404 media when debug is FALSE
I've a trouble with django and I don't know how to fix it. I use DJANGO 3.2.8 and Python 3.7.12 I code an app that allow a user to upload some file into my DB and when an admin are login he can select an user and clic on ID then it's display the user's ID. When I turn DEBUG = True, everything is ok but when I turn DEBUG = False, I've an 404 error when I try to display the user's ID and I don't know how to fix, I try many thing but nothing work (I use collectstatic for the CSS and it's work when DEBUG = FALSE I've got all my pictures ...) My ID are save in media folder. Setting BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') STATIC_URL = 'staticfiles/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) Model def path_and_rename(path, prefix): def wrapper(instance, filename): ext = filename.split('.')[-1] project = "pid_%s" % (instance.name,) # get filename if instance.pk: complaint_id = "cid_%s" % (uuid.uuid4().hex,) filename = '{}.{}.{}.{}'.format(prefix, project, complaint_id, ext) else: # set filename as random string random_id = "rid_%s" % (uuid.uuid4().hex,) filename = '{}.{}.{}.{}'.format(prefix, project, random_id, ext) … -
Whats the point of using a virtual environment for flask and django?
I just want to try out django and or flask but all the videos I see say that I need to get a virtual env. I don't see the point and I don't really want to get one but all of the tutorials say I need one. Can someone explain too me if using a virtual env is required and if it is not what are the pros?