Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
RuntimeError: Model class myapp.models.class doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
This error has been addressed a lot of times but none of the answers seems to applied to me. I am fairly experienced with Python 2 and 3. I used django for the first time.I started making a project. As i was working with a basic DB and after i called the class.objects for the first time the title error occurred. After some time trying to fix it i moved to the django tutorial and i decided to do everything step by step. The error occured again specifically at "Writing your first Django app, part 3" right befor using render. Directories: \home_dir \lib \Scripts \src \.idea \pages \polls \migrations __init__.py admin.py apps.py models.py test.py views.py \templates \django_proj __init__.py asgi.py manage.py settings.py urls.py wsgi.py __init__.py db.sqlite3 manage.py Do not bother with pages it's a test app. django_proj\settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', # My App 'polls' 'pages' ] TEMPLATES and DATABASES are well configured polls\apps.py: from django.apps import AppConfig class PollsConfig(AppConfig): name = 'polls' polls\manage.py from django.db import models from django.utils import timezone import datetime # Create your models here. class Question(models.Model): question_text = models.CharField(max_length=200) published_date = models.DateTimeField('date published') objects = models.Manager() def __str__(self): return self.question_text … -
AttributeError Django
Getting "Generic detail view ItemDetailView must be called with either an object pk or a slug in the URLconf". #models.py class Pic(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) file_type = models.CharField(max_length=100) caption = models.CharField(max_length=100) is_favorite = models.BooleanField(default=False) def get_absolute_url(self): return reverse('picture:item-detail', kwargs={ 'pk2': self.pk}) def __str__(self): return self.caption #views.py class ItemDetailView(generic.DetailView): model = Pic template_name = 'picture/pic.html' #urls.py urlpatterns = { url(r'item/(?P<pk2>[0-9]+)/$', views.ItemDetailView.as_view(), name='item-detail'), } -
Can different Django apps serve the same URL for different MIME types?
I want a URL, say /users/fred, to serve different content based on the Accept header. If the requested MIME type is application/activity+json, I want to serve an ActivityPub representation of Fred's account; otherwise, I want to serve an HTML page. The twist is that I want to implement the ActivityPub view and the HTML view in different Django apps. If they were at different URLs, this would be easily done with urls.py, but that doesn't seem to allow filtering by Accept. Is there a standard way to do this? Do I need to implement something new in middleware? -
CSS Styling not being applied to parts of my html file
I'm using flask's {%extends%} tag to create an index HTML page, and extend styling from the base.html; however, the styling does not seem to be applying to certain parts of the page. I've used HTML and CSS before but this is the first time I am using it with flask as I am creating a python application. I am trying to style the bottom section of the page, but the styling does not apply. Here is my base.html code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Taster Day Booking System</title> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <link href="{{ url_for('static', filename='css/styles.css') }}" rel="stylesheet"> <link rel="shortcut icon" href="{{ url_for('static', filename='images/favicon.ico') }}"> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"> </head> <body> <nav class="navbar navbar-default navbar-fixed-top topnav" role="navigation"> <div class="container topnav"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs- example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand topnav" href="{{ url_for('home.homepage') }}">Home</a> </div> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> {% if current_user.is_authenticated %} {% if current_user.is_admin %} <li><a href="{{ url_for('home.admin_dashboard') }}">Dashboard</a></li> <li><a href="{{ url_for('admin.list_tasterdays') }}">Taster Days</a></li> <li><a href="{{ url_for('admin.list_courses') }}">Courses</a></li> <li><a href="{{ url_for('admin.list_students') }}">Students</a></li> {% else %} <li><a href="{{ url_for('home.dashboard') }}">Dashboard</a></li> {% endif %} <li><a href="{{ url_for('auth.logout') }}">Logout</a></li> <li><a><i class="fa fa-user"></i> Hi, {{ current_user.username }}!</a></li> {% … -
Docker Django NGINX Postgres build with scaling
I have worked mostly with monolithic web applications over the years and have not spent very much time looking at Django high-availability scaling solutions. There are plenty of NGINX/Postgres/Django/Docker builds on hub.docker.com but not one that I could find that would be a good starting point for a scalable Django web application. Ideally the Docker project would include: A web container configuration that easily allows adding new web containers to web app A database container configuration that easily allows adding new database shards Django microservice examples would also be a plus Unfortunately, I do not have very much experience with Kubernetes and Docker swarms. If there are none, I may make this my next github.com project. Thank you in advance. -
Model.clean() vs Model.clean_fields()
What is the difference between the Model.clean() method and the Model.clean_fields() method?. When should I use one or the other?. According to the Model.clean_fields() method documentation: This method will validate all fields on your model. The optional exclude argument lets you provide a list of field names to exclude from validation. It will raise a ValidationError if any fields fail validation. . . . So the Model.clean_fields() method is used to validate the fields of my model. According to the Model.clean() method documentation: This method should be used to provide custom model validation, and to modify attributes on your model if desired. For instance, you could use it to automatically provide a value for a field, or to do validation that requires access to more than a single field . . . But, this method should be used to make other validations, but among those, you can perform validations to different fields. And in the Django examples of the Model.clean() method, validations are made to fields: class Article(models.Model): ... def clean(self): # Don't allow draft entries to have a pub_date. if self.status == 'draft' and self.pub_date is not None: raise ValidationError(_('Draft entries may not have a publication date.')) # Set … -
Django - URL configuration
Here is something i wanna ask if i try this code i can go to login page but my url look like this http://127.0.0.1:8000/%2Flogin/. What is this %2F? urlpatterns = [ path("", views.index, name="index"), path("<str:slug>", views.redirect, name='redirect'), path('/login/', views.logIn, name='login')] And i remove slash from login url i get an error message Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000//login/ after removing slashes here is the code urlpatterns = [ path("", views.index, name="index"), path("<str:slug>", views.redirect, name='redirect'), path('login', views.logIn, name='login')] So, i wanna know is that why are the slashes affecting the url for login but not <str:slug> -
I am not getting any error but also not getting any blog, Problem with pagination
I am not getting any error with this code, but also not getting any result it is not showing any of my blog on-page. I think HTML code is misplaced. my pagination is not working properly before it throws an error of order then I ordered it by date and now it is not displaying anything and not throw any error which makes it's difficult to fix main.html <!DOCTYPE html> {% load static %} <link rel="shortcut icon" href="{% static 'img/favicon.png' %} "> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>Advice Lancing</title> <!-- <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> --> <!-- Bootstrap Core CSS --> <link type="text/css" href="{% static 'vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet"> <!-- Theme CSS --> <link href="{% static 'css/clean-blog.min.css' %}" rel="stylesheet"> <!-- Custom Fonts --> <link href="{% static 'vendor/font-awesome/css/font-awesome.min.css' %}" rel="stylesheet" type="text/css"> <link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> <style> img { border: 1px solid #ddd; /* Gray border */ border-radius: 10px; /* … -
How to query postgres RangeField using Hasura GraphQL
Python3 django==3.0.5 Hasura v1.1.1 postgres==11.3 I am trying to use Hasura filter on the IntegerRangeField() and DecimalRangeField(), but stuck at first one from django.contrib.postgres.fields import DecimalRangeField, IntegerRangeField from django.db import models class MyModel(modles.Model): age = IntegerRangeField() ... In browser I query with this payload query MyQuery { insurance_life_premium(where: {age: {_eq: "47"}}) { percentage_rate plan_id policy_term premium sum_insured } } It raises error { "errors": [ { "extensions": { "path": "$", "code": "data-exception" }, "message": "malformed range literal: \"47\"" } ] } I confirm that my database has valid data In [1]: Premium.objects.filter(age__contains=47) Out[1]: <QuerySet [<Premium: Premium object (1)>, <Premium: Premium object (60)>, <Premium: , <Premium: Premium object (878)>, '...(remaining elements truncated)...']> In terminal it mentions about parentheses hasura_1 | {"type":"http-log","timestamp":"2020-04-29T17:19:08.094+0000","level":"error","detail":{"operation":{"user_vars":{"x-hasura-role":"admin"},"error":{"path":"$","error":"malformed range literal: \"47\"","code":"data-exception"},"request_id":"aab2de87-1095-423e-9eb1-dae34926b226","response_size":78,"query":{"operationName":"MyQuery","query":"query MyQuery {\n insurance_life_premium(where: {age: {_eq: \"47\"}}) {\n percentage_rate\n plan_id\n policy_term\n premium\n sum_insured\n }\n}\n"}},"http_info":{"status":200,"http_version":"HTTP/1.1","url":"/v1/graphql","ip":"172.22.0.1","method":"POST","content_encoding":null}}} postgres_1 | 2020-04-29 17:19:08.095 UTC [34] ERROR: malformed range literal: "47" postgres_1 | 2020-04-29 17:19:08.095 UTC [34] DETAIL: Missing left parenthesis or bracket. postgres_1 | 2020-04-29 17:19:08.095 UTC [34] STATEMENT: SELECT coalesce(json_agg("root" ), '[]' ) AS "root" FROM (SELECT row_to_json((SELECT "_1_e" FROM (SELECT "_0_root.base"."percentage_rate" AS "percentage_rate", "_0_root.base"."plan_id" AS "plan_id", "_0_root.base"."policy_term" AS "policy_term", "_0_root.base"."premium" AS "premium", "_0_root.base"."sum_insured" AS "sum_insured" ) AS "_1_e" ) ) AS … -
how to filter list in Mysql in Django
class Student(): name=models.CharField(max_length=200) surname=models.CharField(max_length=200) class group2020(): name=models.CharField(max_length=200) math=models.DecimalField(decimal_places=2,max_digits=1000) english=models.DecimalField(decimal_places=2,max_digits=1000) biology=models.DecimalField(decimal_places=2,max_digits=1000) chemistry=models.DecimalField(decimal_places=2,max_digits=1000) class group2019(): name=models.CharField(max_length=200) math=models.DecimalField(decimal_places=2,max_digits=1000) english=models.DecimalField(decimal_places=2,max_digits=1000) biology=models.DecimalField(decimal_places=2,max_digits=1000) chemistry=models.DecimalField(decimal_places=2,max_digits=1000) class group2018(): name=models.CharField(max_length=200) math=models.DecimalField(decimal_places=2,max_digits=1000) english=models.DecimalField(decimal_places=2,max_digits=1000) biology=models.DecimalField(decimal_places=2,max_digits=1000) chemistry=models.DecimalField(decimal_places=2,max_digits=1000) If i added other classes that represents years 2020,2019,2018 of a group grades, i combined them in list and made calculations. math=[group2020.math,group2019.math,group2018.math] english=[group2020.english,group2019.english,group2018.english] chemistry=[group2020.chemistry,group2019.chemistry,group2018.chemistry] type_1=list(map(lambda n,m:n/m,math,english )) type_2=list(map(lambda n,a:n/a,chemistry,math )) How to filter the ready list based on type_1 > 2 and type_2 < 1 ? -
Pandas to_csv method's option quoting=csv.QUOTE_MINIMAL is NOT working
Pandas to_csv method's option quoting=csv.QUOTE_MINIMAL is NOT working. I have following input tab delimited data, In the following example -> denotes tab and . denotes space chars. Jhon->35->123.Vroom.St->01120 After using to_csv method and option quoting=csv.QUOTE_MINIMAL I am expecting following output. Jhon 35 "123 Vroom St" 01120 Which means quote only address values where there is space in the delimited data and do not quote if no space. df.to_csv(file, sep='\t', header=False, index=False, quoting=csv.QUOTE_MINIMAL) However, I am getting following output. There is no quote on the address. Jhon 35 123 Vroom St 01120 Using option quoting=csv.QUOTE_ALL getting me below which I don't want. "Jhon" "35" "123 Vroom St" "01120" Could someone please help me what's wrong here or this is a panda bug? Thanks. -
Why is not rendering the template
This is my create view I want to call each form one at a time. on getting to the second step organizer form after submitting the form, it does nothing instead of rendering the next form and html what I wanted to do is create venue_form, create organizer_form save it and populate them to event before saving event_form but event_form template is not rendering. What am I doing wrong. def create_event(request, step=None): venue_form = VenueForm() organizer_form = OrganizerForm() event_form = EventForm() ctx = { 'venue_form': venue_form, 'organizer_form': organizer_form, 'event_form': event_form, } if request.method == "POST": venue_form = VenueForm(request.POST) return render(request, 'event/organizer_form.html', ctx) if request.method == "POST": organizer_form = OrganizerForm(request.POST) return render(request, 'event/event_form.html', ctx) else: return render(request, 'event/venue_form.html', ctx) -
MultiSelectField On Django Admin Not Showing Values
I am seeing my list's key (permit_num and passport_num) instead of my values (Work Permit and Passport) on my Django admin. How do I fix this? For docs_good, it is showing "Yes" or "No". So it is good to me. Everything else is doing fine but only for this one. Perhaps because I use an external package? Here is my view.py: from django.db import models from multiselectfield import MultiSelectField class Case(models.Model): doc_choices = ( ('permit_num', 'Work Permit'), ('passport_num', 'Passport'), ) doc_listed = MultiSelectField("Documents Received?", choices=doc_choices, default=False) doc_good_choices = ( ('y', 'Yes'), ('n', 'No'), ) docs_good = models.CharField("Documents Good To Go?", max_length=264, choices=doc_good_choices,default=False) My admin.py script: class CaseAdmin(admin.ModelAdmin): model = Case list_display = ('doc_listed', 'docs_good') admin.site.register(Case, CaseAdmin) -
Accessing Moodle web service via django
Im trying to access moodle via moodle-ws-client package but im getting this error -
Django return redirect and Pop Up
under my views.py i have a def that will actually do some config into a device, i`m saving the output under a variable for the results and i would like to redirect to "home" when the request is done and at the same time create an html pop-up that will display the results. Expl: under views.py i have the follow code: def pstn_nanp_pri_ca(request): if request.method == "POST": result = [] selected_device_id = request.POST['device'] circuit_id = request.POST['circuit_id'] pri_channel = request.POST['pri_channel'] dev = get_object_or_404(Device, pk=selected_device_id) PSTN_slot = dev.PSTN_Slot # dev.ip_address dev.username, dev.password, dev.site_code try: ` ip_address = dev.ip_address # STATIC Username and Password username = dev.username password = dev.password # # Initiate SSH Connection to the router # ssh_client = paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh_client.connect(hostname=ip_address, username=username, password=password) print("Successful connection", ip_address) remote_connection = ssh_client.invoke_shell() time.sleep(2) remote_connection.send("configure terminal\n") time.sleep(2) # # # PRI Config # # remote_connection.send("card type t1 0 " +str(PSTN_slot[2])+ "\n") remote_connection.send("isdn switch-type primary-ni\n") remote_connection.send("controller T1 " +str(PSTN_slot)+ "\n") remote_connection.send("Description ## PRI Circuit ID : " +str(circuit_id)+ " ###\n") remote_connection.send("framing esf\n") remote_connection.send("clock source line primary\n") remote_connection.send("linecode b8zs\n") remote_connection.send("cablelength long 0db\n") remote_connection.send("pri-group timeslots 1-" +str(pri_channel)+ "\n") time.sleep(2) remote_connection.send("voice-card 0/1\n") remote_connection.send("dsp services dspfarm\n") remote_connection.send("voice-card 0/4\n") remote_connection.send("dsp services dspfarm\n") remote_connection.send("interface Serial" +str(PSTN_slot)+":23\n") remote_connection.send("description ## PRI Circuit ID … -
send out vCard card text messages to mobile phones
I need the code written to send Vcard via text message. I brought the gig but i am not able to fill out the requirements. I need the text messages to come from the number i have paid for in call tools. There support time can answer any questions. Can someone know how to do this in python? -
how to update a model data from the admin panel in django
so i was creating a ecommerce site , what i wanted to do was when i added a product through admin panel , it would increase the count as well from model. eg: in the below model ,when i add an a item from admin panel i want it to find the object and add the objects stock with the new stock number i provided , if both these added items have the same names. class Item(models.Model): name = models.CharField(max_length=100) price = models.FloatField() product = models.ForeignKey(Product, on_delete=models.CASCADE) desc = models.TextField() img = models.ImageField(upload_to='uploads/items', blank=True) stock = models.IntegerField() def __str__(self): return self.name -
Making a new variable per unique value in database with django
Thank you for taking your time to read this. My Situation: I have a function in my view, that can export a table to a .xml file. It now just takes all the data and throw it in a file and exporting it to a single file. Let me show a bit of related code: views.py def export_shipments_xls(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="shipments.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('NewShipment') # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = [ 'Order ID', 'Full Name', 'Street', 'Postal Code', 'City', 'E-mail', 'Telephone', ] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # Sheet body, remaining rows font_style = xlwt.XFStyle() rows = models.NewShipment.objects.all().values_list( 'increment_id', 'full_name', 'street', 'zip_code', 'city', 'email', 'telephone', ) for row in rows: row_num += 1 for col_num in range(len(row)): ws.write(row_num, col_num, row[col_num], font_style) wb.save(response) return response Models.py class NewShipment(models.Model): increment_id = models.CharField(max_length=9) full_name = models.CharField(max_length=75) street = models.CharField(max_length=75) zip_code = models.CharField(max_length=4) city = models.CharField(max_length=20) email = models.CharField(max_length=50, blank=True, null=True) telephone = models.CharField(max_length=15, blank=True, null=True) date = models.DateTimeField(auto_now_add=True) products = models.CharField(max_length=50) country = models.CharField(max_length=8, blank=True, null=True) lost_because_of = models.CharField(max_length=100, blank=True, null=True) custom_comment = models.CharField(max_length=200, blank=True, null=True) exported = models.BooleanField(default=False) def __str__(self): return self.increment_id … -
Heroku pg_restore not restoring data to some tables
I'm trying to restore a database from heroku, but much of the data is being lost in the process. I've checked the output of the pg_restore command and all the data is in the dump, but it is not properly restoring. I am using django. and trying to get the server to run locally with django. I can get it running if I create a new database, run migrations, then use this command: pg_restore --verbose --data-only --no-acl --no-owner -h localhost -U mrp -d mrp latest.dump.1 This sets up all the tables correctly as far as I can tell, and includes some of the data needed, but other data is lost. When I run pg_restore with --clean instead of --no-data It messes up the tables and I get this error whenever I use manage.py commands: psycopg2.IntegrityError: null value in column "id" violates not-null constraint and django.db.utils.IntegrityError: null value in column "id" violates not-null constrain Here are some examples of errors when I run pg_restore with the --data-only command: pg_restore: [archiver (db)] Error while PROCESSING TOC: pg_restore: [archiver (db)] Error from TOC entry 4113; 0 2654299 TABLE DATA auth_group_permissions tbjatcnpbztfzf pg_restore: [archiver (db)] COPY failed for table "auth_group_permissions": ERROR: insert or update … -
How to check if the uuid generated is unique?
I'm generating another id on top of the primary key for security purposes like this: uid = models.CharField(max_length=10, default=uuid.uuid4().hex[:8], editable=False) but how to check if it's unique? -
Remove duplicates from multiple fields and return the queryset in Django
I have query that I send through context as follows: TravelData.objects.exclude(Q(from_lat__isnull=True) | Q(from_long__isnull=True) | Q(to_lat__isnull=True) | Q(to_long__isnull=True)).values('from_lat', 'from_long', 'to_lat', 'to_long') Here there are multiple values of (from_lat and from_long) and (to_lat and to_long). I would like to add the similar values only once i.e., I must check for both from values and to values at a time and exclude if it is present. In the frontend I am rendering these locations on a map the co-ordinates of the point will be [from_long, from_lat] or [to_long, to_lat] How can I change the above query to get the most efficient queryset? -
NoReverseMatch: Reverse for 'cart_add' with arguments '(3,)' not found. 1 pattern(s) tried: ['cart/add/<product_id>/']
I am creating an online shop, but when I try to load my product page I get the following error. I believe the error is pointing to my namespace but every way I try to correct it, I still get the error I have 2 apps cart and shop. There is almost the same question on stackoverflow NoReverseMatch at /product_view/1/ Reverse for 'cart_add' with arguments '('',)' not found. 1 pattern(s) tried: [u'cart/add/(?P<product_id>\\d+)/$'] , but sollutions on it does not help me. Thanks for understanding. here is cart's app views: from django.shortcuts import render, redirect, get_object_or_404 from django.views.decorators.http import require_POST from shop.models import Product from .cart import Cart from .forms import CartAddProductForm @require_POST def cart_add(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update']) return redirect('cart:cart_detail') def cart_remove(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) cart.remove(product) return redirect('cart:cart_detail') def cart_detail(request): cart = Cart(request) for item in cart: item['update_quantity_form'] = CartAddProductForm( initial={ 'quantity': item['quantity'], 'update': True }) return render(request, 'cart/detail.html', {'cart': cart}) cart app urls.py: from django.conf.urls import url from . import views app_name = 'cart' urlpatterns = [ url('', views.cart_detail, name='cart_detail'), url('add/<product_id>/', views.cart_add, name='cart_add'), url('remove/<product_id>/', views.cart_remove, name='cart_remove'), ] My project … -
Django - importing models
After having built some quiz and job post, I noticed that with the following code that you will see, if the user score is > 1 I would like the user to see the job_offer but as you can see in the picture, it shows all the job_offers for all the categories. I would like to show only the job offer related to the category. So if you have a score > 1 in the "data science" quiz, you will see only the job_offer related to "data science". My problem here is to link the specific category to the job_offer I tried to import the quiz/models.py in my jobs/models.py and tried to link the job_post with the category but it didn't work. quiz/models.py from django.contrib.auth.models import User from django.db import models # Create your models here. class Questions(models.Model): CAT_CHOICES = ( ('datascience', 'DataScience'), ('productowner', 'ProductOwner'), ('businessanalyst', 'BusinessAnalyst'), #('sports','Sports'), #('movies','Movies'), #('maths','Maths'), #('generalknowledge','GeneralKnowledge'), ) question = models.CharField(max_length = 250) optiona = models.CharField(max_length = 100) optionb = models.CharField(max_length = 100) optionc = models.CharField(max_length = 100) optiond = models.CharField(max_length = 100) answer = models.CharField(max_length = 100) catagory = models.CharField(max_length=20, choices = CAT_CHOICES) student = models.ManyToManyField(User) class Meta: ordering = ('-catagory',) def __str__(self): return self.question … -
.env is not being detected in Django
I have done pip install python-dotenv and then created a .env file in the same folder as the settings.py. The values from the .env is not working. settings: SECRET_KEY = os.environ.get('SECRET_KEY') .env file: SECRET_KEY=mysecretkey What should I do? -
custom authentication backend
I have a web system that has 2 logins, one of them is normal with username and password, the other login would only be with a field called rfid, at the moment I am testing with the username field, then I will change it for the field rfid. If what I'm trying to do is log in without a password, for this I implemented a backend to be able to log in a user without a password, just that he hasn't let me log in yet and keeps asking me for the password. Backend from django.contrib.auth.backends import ModelBackend from django.contrib.auth.models import User class PasswordlessAuthBackend(ModelBackend): def authenticate(self, username=None): try: return User.objects.get(username=username) except User.DoesNotExist: return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None settings.py AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.ModelBackend', 'myproject.auth_backend.PasswordlessAuthBackend'] view.py def login_rfid(request, username=None): if request.method == 'POST': form = AuthenticationForm(data=request.POST or request.GET or None) if form.is_valid(): form.save() username = form.cleaned_data.get('username') user = authenticate(username=username) if user is not None: ogin(request, user) return redirect('home') else: form = AuthenticationForm() return render(request, "registration/login_rfid.html", {'form': form}) html <form method="post" action="{% url 'login_rfid' %}"> {% csrf_token %} <div> <td>{{ form.username.label_tag }}</td> <td>{{ form.username }}</td> </div> <div> <input type="submit" value="login"/> {# <input type="hidden" name="next" value="{{ next }}" …