Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get reason data on failure transaction
With paypal-ipn, I am using paypal payment integration in my django application. I can track data on successful transaction through POST call but on failure transaction it return request in get method with no data. I need help to get the reason for failing transactions on failure transaction -
Is there any way to login to Django admin interface using username or email?
I want to implement a login system to login to Django admin via email or username. Does anyone know how to implement it. I use custom user model. I know how to allow user to login to website using username or email. But it doesn't work in Django admin interface -
How can I edit the css of an django form error message`?
I have a form on my Django app, which should allow users upload only csv files and whenever a user uplaods a file with a different extension, I want to render an error message. Currently I check the extention of the file which is uploaded and if the extension is not .csv then I add an error in the ValidationErrors The problem is that I can not find a way to edit the css of that error. Right now it is being displayed as an element of a list but I would like to put it in h1 tags. Here is my code: forms.py from django import forms from .models import CSVUpload import time class CsvForm(forms.ModelForm): csv_file = forms.FileField(widget=forms.FileInput( attrs= { 'class': 'form-group', } )) class Meta: model = CSVUpload fields = ('csv_file', ) def save(self): csvfile = super(CsvForm, self).save() return csvfile def clean_csv_file(self): uploaded_csv_file = self.cleaned_data['csv_file'] if uploaded_csv_file: filename = uploaded_csv_file.name if filename.endswith('.csv'): return uploaded_csv_file else: raise forms.ValidationError("File must be csv") else: return uploaded_csv_file template {% extends "fileconverter/base.html" %} {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.csv_file }} {{ form.csv_file.errors }} <button type="submit" class="uploadbutton">Convert CSV</button> </form> {% endblock %} Could someone help me understand how … -
Django migration error,auth_permission_content_type_id_codename_01ab375a_uniq duplicated key
I am trying to migrate my module to PostgresSQL but when I do I got an error that teling me the key unique "auth_permission_content_type_id_codename_01ab375a_uniq" is duplicated . the key (content_type_id, codename)=(1,view_arrets) are existed . The code somehow create a duplicates views . my modules are : from django.db import models from django.urls import reverse class ProfilsHoraires(models.Model): P_id = models.AutoField(primary_key=True) id_profil = models.CharField(unique=True,max_length=120) d_p_1 = models.TimeField() f_p_1 = models.TimeField() d_p_2 = models.TimeField() f_p_2 = models.TimeField() class Meta: db_table = 'profilsHoraires' ordering = ['P_id'] def get_absolute_url(self): return reverse("profiles-edit", kwargs={"P_id": self.P_id}) class categorie(models.Model): Categorie = models.CharField(primary_key=True,max_length=20, blank=True) class Meta: db_table = 'categorie' ordering = ['Categorie'] def get_absolute_url(self): return reverse("categorie-edit", kwargs={"id": self.Categorie}) class Destination(models.Model): destinationNom=models.CharField(primary_key=True,max_length=90, blank=True) class Meta: db_table = 'disination' ordering = ['destinationNom'] def get_absolute_url(self): return reverse("destination-edit", kwargs={"id": self.destinationNom}) class Collaborateurs(models.Model): mle = models.AutoField(primary_key=True) nom = models.CharField(max_length=90, blank=True, null=True) prenom = models.CharField(max_length=90, blank=True, null=True) address = models.TextField(blank=True, null=True) latitude = models.FloatField(blank=True, null=True) longtitude = models.FloatField(blank=True, null=True) libele_dest = models.ForeignKey(Destination, on_delete=models.SET_NULL, null=True) profil = models.ForeignKey(ProfilsHoraires, on_delete=models.SET_NULL, null=True) class Meta: db_table = 'collaborateurs' ordering = ['mle'] def __unicode__(self): return self.title def get_absolute_url(self): return reverse("collabs-edit", kwargs={"mle": self.mle}) class Vehicules(models.Model): V_id = models.AutoField(primary_key=True) allocation= models.FloatField(null=False) capacite = models.IntegerField(null=False) type = models.CharField(max_length=20, blank=True, null=False) class Meta: db_table = … -
How to set up Django model inheritance with foreign key
I have three models, one superclass and two subclasses. Both subclasses belong to another model (expressed through a foreign key). I am not really sure what the best setup would look like in regards to my FK? Do I put the foreign key in the superclass, in the subclass, or in both? Every building can have many energy objects, which means it can have many Heating and Cooling objects. Every Heating/Cooling/Energy object belongs to one building. So a classic One-to-many relationship expressed with a Foreign Key. Here are my models: Superclass class Energy(models.Model): year : models.BigIntegerField(...) value : models.IntegerField(...) connected_building : ForeignKey ?????? Subclasses class Heating(Energy): connected_building : ForeignKey ????? class Cooling(Energy): connected_building : ForeignKey ????? Related class class Building(models.Model): name = models.Charfield(...) I am kind of scared of messing up my db, so any help is highly appreciated. Thanks in advance! -
'ProjectFormFormSet' object has no attribute 'request'
I want to add to my project one feature that only authenticated users can have access their stuff. But when I write queryset it throws an error like ModelNameFormSet object has no request attribute views.py class BaseAuthorFormSet(BaseModelFormSet): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.queryset= Project.objects.filter(author_id=self.request.user.pk) def add_object(request): ProjectFormSet = modelformset_factory(Project, formset=BaseAuthorFormSet, fields=( 'service_name', 'service_code', 'report_month', 'report_year', 'last_year'), extra=1) if request.method == "POST": form = ProjectFormSet(request.POST) form.author = request.user if form.is_valid(): form.save() form = ProjectFormSet() return render(request, 'app1/home.html',{'form':form}) I have only this code. How can I solve this issue? Thank you beforehand! -
How do i Accept payments in my Django website
I just finished learning, python and django and i am currently doing a small project to get better experience with backend web development. I created a registration portal for a Festival, where users register themself and select events they want to participate. I want to create an online payment option so that users can pay online for the events they want to participate in. I researched on the internet for some online payment gateway that i can implement on my website. I decided to use Razorpay as it was recommended by many people. I want to accept all kind of credit/ debit and UPI payments. The documentation are not begineer friendly. So i need a detail step by step guide on how i can do this. -
image filed returns null
i Have a model like this:i'm trying to create sign up with this fields: username first name and last name and email and address and profile image class User(AbstractUser): username = models.CharField(blank=True, null=True, max_length=50) Email = models.EmailField(_('email address'), unique=True) Address = models.CharField(max_length=100, default="") UserProImage = models.ImageField(upload_to='accounts/',blank=True, null=False) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['Email', 'first_name', 'last_name', 'Address', 'UserProImage'] def __str__(self): return "{}".format(self.username) def get_image(self, obj): try: image = obj.image.url except: image = None return image def perform_create(self, serializer): serializer.save(img=self.request.data.get('UserProImage')) and for this model i wrote a serilaizer with like this: class UserCreateSerializer(ModelSerializer): Email = EmailField(label='Email Address') ConfirmEmail = EmailField(label='Confirm Email') class Meta: model = User fields = [ 'username', 'first_name', 'last_name', 'Address', 'UserProImage', 'Email', 'ConfirmEmail', 'password', ] extra_kwargs = {"password": {"write_only": True} } objects = PostManager() def __unicode__(self): return self.username def __str__(self): return self.username def validate(self, data): return data def perform_create(self, serializer): serializer.save(self.request.data.get('UserProImage')) return self.data.get('UserProImage') def validate_email(self, value): data = self.get_initial() email1 = data.get('ConfirmEmail') username = data.get('username') email2 = value if email1 != email2: raise ValidationError("Emails must match.") user_qs = User.objects.filter(email=email2) username_qs = User.objects.filter(username=username) if user_qs.exists(): raise ValidationError("This user has already registered.") if username_qs.exists(): raise ValidationError("This user has already registered.") return value def validate_email2(self, value): data = self.get_initial() email1 = data.get('Email') … -
NOT NULL constraint failed: loginpage_location.org_id
I am new to django and learning to get a hang of the entire thing. I am not really sure why the problem is existing. I have looked up in a few stackoverflow questions, but me being a novice, i couldn't understand much from the explanation. I would like to know the 'why' alongwith the 'how' if possible. views.py def orgdataentry(request): if request.user.is_authenticated: orgdataform = OrgDataEntryForm(data=request.POST or None) orglocform = OrgLocEntryForm(data=request.POST or None) if orgdataform.is_valid() and orglocform.is_valid(): #fs = orgdataform.save(commit=False) #fs.user = request.user orgdataform.save() orglocform.org = request.POST['org_name'] #fs = orglocform.save(commit=False) #fs.user = request.user orglocform.save() return HttpResponse('Success') else: return render(request, 'org_login/dataentry.html', {'orgdataform': orgdataform, 'orglocform': orglocform}) else: return redirect('login') I have tried running the code with the commented code lines as well but no luck forms.py class OrgDataEntryForm(forms.ModelForm): class Meta: model = Organization db_table = 'Organization Details' fields = 'all' class OrgLocEntryForm(forms.ModelForm): class Meta: model = Location db_table = 'Organization Locations' exclude = ['org'] And models.py class OrgType(models.Model): org_type_id = models.AutoField(primary_key=True) org_external = models.BooleanField(default=True) org_sector = models.CharField(max_length=50, default='', verbose_name='Sector') org_type_des = models.CharField(max_length=50, null=True, verbose_name='Sector Description') def __str__(self): return self.org_sector class Organization(models.Model): org_id = models.AutoField(primary_key=True) org_name = models.CharField(max_length=50, default='', verbose_name='Company Name') org_type = models.ForeignKey(OrgType, on_delete=models.CASCADE, verbose_name='Company Type') org_inc_date = models.DateField(blank=True, null=True, verbose_name='Incorporation Date', … -
First query in Django is always slow
I have a simple Django app, just two models and a view. Whenever I query the db, the first query always takes about a second, and any query after that is almost instantaneous. My view looks like this: def my_view(request): start = time.time() print('0', time.time() - start) a = TestClass.objects.get(name="test") print('1', time.time() - start) b = TestCustomer.objects.get(name="test") print('2', time.time() - start) return render(request, 'test.html', {}) When I run it, I get the following output: 0 0.0 1 1.0049302577972412 2 1.0059285163879395 which means that the first query is much slower than the second one. If I comment out the first query, (the TestClass query), I get the following output: 0 0.0 1 0.0 2 1.0183587074279785 meaning that the TestCustomer query suddenly got a lot slower. Both models have one field only (name, which is a CharField). How come the first query is always so much slower? I have tried disabling Debug but that makes no difference. And if I run the queries directly, bypassing Django, they're instantaneous: SELECT `customers_testcustomer`.`id`, `customers_testcustomer`.`name` FROM `customers_testcustomer` WHERE `customers_testcustomer`.`name` = 'test'; /* Affected rows: 0 Found rows: 1 Warnings: 0 Duration for 1 query: 0,000 sec. */ -
slow django developent server
my django development server has just started running extremely slow (a number of minutes to load a page). Yesterday it was working fine, as it has been for the past 1-2 years. I/m at a loss as to what might to causing this so unsure where to even start looking to troubleshoot. I'm on ubuntu 18.04 and as far as I am aware there have been no software updates overnight. Internet speed is still blistering fast so that doesnt seem to be the issue. I'd appreciate any ideas for things I could start to look into to try and resolve this. -
Troubles with serializer for proxy models DRF/DJANGO
I have a question regarding serializes in DRF: I have a following Models: class Heading(models.Model): name = models.CharField(max_length=20, db_index=True, unique=True, verbose_name='heading ' 'title') order = models.SmallIntegerField(default=0, db_index=True, verbose_name='Order') foreignkey = models.ForeignKey("UpperHeading", on_delete=models.PROTECT, null=True, blank=True, verbose_name="Upper heading", ) one_to_one_to_boat = models.OneToOneField(BoatModel, on_delete=models.SET_NULL, null=True,blank=True, verbose_name="correspondent boat for the category", ) change_date = models.DateTimeField(db_index=True, editable=False, auto_now=True) # primary model class UpperHeadingManager(models.Manager): def get_queryset(self): return models.Manager.get_queryset(self).filter(foreignkey__isnull=True) class UpperHeading(Heading): objects = UpperHeadingManager() def __str__(self): return self.name class Meta: proxy = True ordering = ("order", "name") verbose_name = "Upper heading" verbose_name_plural = "Upper headings" # secondary model class SubHeadingManager(models.Manager): def get_queryset(self): return models.Manager.get_queryset(self).filter(foreignkey__isnull=False) class SubHeading(Heading): objects = SubHeadingManager() def __str__(self): return "%s - %s" % (self.foreignkey.name, self.name) class Meta: proxy = True ordering = ("foreignkey__name", "name") verbose_name = "Sub heading" verbose_name_plural = "Sub headings" I want to make serializer for the model Upperheading in a such way that it would include secondary model’s “SubHeading” related data Here is what I written: class UpperHeadingSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) name = serializers.CharField(max_length=20, required=True, allow_blank=False) order = serializers.IntegerField() subheading_set = serializers.PrimaryKeyRelatedField(many=True, read_only=True) def create(self, validated_data): return UpperHeading.objects.create(**validated_data) def update(self, instance, validated_data): instance.name = validated_data.get("name", "instance.name") instance.order = validated_data.get("order", "instance.order") instance.save() return instance class Meta: model = UpperHeading fields = ("id", … -
Unusual behavior of form during the update of the content already published
I'm developing the backend of my personal blog and, using this tutorial for the date and time, I've created a form for the creation of a blog post. I notice two things: If I try to update an existing post the publishing date field is blank into the form but I can see the publication date in the details of the post. If I try to update an existing image or document the upload field is blanck Why happen this? create_post.html <form class="" method="POST" enctype="multipart/form-data" novalidate>{% csrf_token %} <div class="form-group"> <div class="row"> <div class="col-sm-9"> <div class="form-group mb-4"> <div>{{ form.title }}</div> <label for="id_title"> <span class="text-info" data-toggle="tooltip" title="{{ form.title.help_text }}"> <i class="far fa-question-circle"></i> </span> <small class="text-danger">{{ form.title.errors }}</small> </label> </div> <div class="form-group mb-4"> <div>{{ form.description }}</div> <label for="id_description"> <span class="text-info" data-toggle="tooltip" data-placement="bottom" title="{{ form.description.help_text }}"> <i class="far fa-question-circle"></i> </span> <small class="text-danger">{{ form.description.errors }}</small> </label> </div> <div class="form-group mb-4"> <div>{{ form.contents }}</div> <label for="id_contents"> <span class="text-info" data-toggle="tooltip" data-placement="bottom" title="{{ form.contents.help_text }}"> <i class="far fa-question-circle"></i> </span> <small class="text-danger">{{ form.contents.errors }}</small> </label> </div> <div class="form-group mb-4"> <div>{{ form.header_image_link }}</div> <label for="id_header_image"> <span class="text-info" data-toggle="tooltip" title="{{ form.header_image_link.help_text|safe }}"> <i class="far fa-question-circle"></i> </span> <small class="text-danger">{{ form.header_image_link.errors }}</small> </label> </div> </div> <div class="col-sm-3"> <div class="form-group mb-4"> <div class=""><h4>{{ … -
Django : How can I put the initial data into database by editting migrations file?
I added 'models' and created a file using 'makemigrations'. I want to have the initial data in the database at the same time as 'migrate'. However, no matter how much I edit the 'migrations' file, there is an error that says no because there is no 'table' in the database before 'migrate'. Help me... -
Django REST Framework serialize multiple foreign keys related between
Let's imagine we have next models: class Radio(models.Model): name = models.CharField(...) class Artist(models.Model): name = models.CharField(...) class Song(models.Model): title = models.CharField(...) artist = models.ForeignKey(Artist, ...) class Reproduction(models.Model): song = models.ForeignKey(Song...) radio = models.ForeignKey(Radio...) date = models.DateTimeField(...) How should I create my serializer and view if I will receive in a POST: title: "Song title", artist:"Artist name", radio:"Radio name", date:"Reproduction date" and it's needed to create the artist and the song if they don't exist. Thank you. -
Django migration error table is already exists
Hi i have only one migration file called 001_initial..... it contains all create table(sql) django makemigrations created when i did makemigrations for example 5 tables [1,2,3,4,5] and i have first(1) already there in my database for example 1, so i need to migrate table for example 2,3,4,5 but i'm getting error when i do python manage.py migrate, error is table one(1) is already created and table 2,3,4,5 not created in the database because of this error i have only one migration file an i deleted the django_migration file data so how to do? -
NOT NULL constraint failed: app_model.author_id
I am trying to make forms only visible to its author but I fail with this error NOT NULL constraint failed: app_myModel.author_id when I add some objects from Django Administration, added objects are visible for all, but in template if I fill the form and click save button it gives me above error. Here what i have tried so far models.py class Project(models.Model): service_name = models.CharField(max_length=100) service_code = models.CharField(max_length=5) report_month = models.CharField(max_length=6) report_year = models.CharField(max_length=6) last_year = models.CharField(max_length=6) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.service_name views.py def add_object(request): ProjectFormSet = modelformset_factory(Project, fields=( 'service_name', 'service_code', 'report_month', 'report_year', 'last_year'), extra=1) if request.method == "POST": form = ProjectFormSet(request.POST) form.author = request.user if form.is_valid(): form.save() form = ProjectFormSet() return render(request, 'app1/home.html',{'form':form}) here what I have. How can I add objects and make visible only for its author. Any help? -
Django Channels, instantiating a new Consumer on the fly, not linked to a Websocket or other protocol?
I am building off the Django Channels Tutorial, trying to add a "Chat Manager" consumer to the tutorial's simple chat app. It would function as a simple chatbot, maybe sending a random message in the chatroom every ten seconds, for example. The idea is that this ChatManagerConsumer would be created once when a new chat room is made, and only one ManagerConsumer exists for the lifespan of the whole chatroom, even as individual users/WebsocketConsumers come and go from the room. I'm not clear on how to go about doing this. Background workers would not work, since it looks like you can't programmatically create multiple instances of a background worker; only one can be spawned from the command line. Instead, I would like to have one Consumer instance running per each chat room. The documentation says "consumers are long-running" and "a chatbot protocol would keep one scope open for the entirety of a user’s conversation with the bot" but doesn't really explain how to open up a consumer for this hypothetical chatbot protocol. Any help would be appreciated! -
django+heroku+postgres error in createsuperuser "
i wanted to deploy my django app in heroku with postgresql ,everything went well , migrations ran fine but when i am trying to createsuperuser it is giving me error (youngmindsenv) E:\young_minds\heroku\youngminds>heroku run bash Running bash on ? youngminds... up, run.8229 (Free) ~ $ python manage.py createsuperuser Username (leave blank to use 'u21088'): johnson Email address: johnson@gmail.com Password: Password (again): Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils .py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "users_profile" does not exist LINE 1: INSERT INTO "users_profile" ("user_id", "image", "descriptio... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/_ _init__.py", line 371, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/_ _init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/b ase.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/mana gement/commands/createsuperuser.py", line 59, in execute return super().execute(*args, **options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/b ase.py", line 335, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/mana gement/commands/createsuperuser.py", line 179, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user _data) File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/mode ls.py", line 161, in create_superuser return self._create_user(username, email, password, **extra_fields) File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/mode ls.py", line 144, in _create_user user.save(using=self._db) File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/base _user.py", line 73, in save super().save(*args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/base.py ", … -
Best way to call a function in specific time in django
in my django project i have a model Task : class Task(models.Model): title = models.CharField(max_length=100) description = models.TextField() expiration_date = models.DateTimeField(default=max_expiration_date) #################################### def max_expiration_date(): now = timezone.now() return now + timezone.timedelta(days=7) exact in expiration date i need call notification function.please be notice i will have too many Task instance so i need the best method for optimal system consumption.what is best way to do that? celery can do this?thank you. -
Does Amazon-SES provide any api to know if the email was successfully sent?
So I am sending a few emails to clients using Amazon-ses. In few cases, I need to know if the email was successfully delivered. Is there any way to know? Does Amazon provide any api that tells me if the email was delivered successfully? Some of the mails I send have critical status. I am using django1.9 and python3. -
Adapting an existing django site for modal forms
I have a site which uses the urls to add/edit/view records to the database. These pass the information to another template for data entry. I'm now looking at modal forms - at the moment we have used css, rather than the Django modal forms. My question, which is basic, is it possible to keep the urls and templates but embed them in the modal? This way we can keep the same code and migrate to modals without recoding the views. I'm looking for a clear simple documentation for this - so please send me any good links. For a basic example (we have more complex views): template storage {% extends 'storage/base.html' %} {% load staticfiles %} {% load widget_tweaks %} {% block content%} {% include "mainheader.html" %} {% include "storage/submenu.html" %} <div class="container top"> <div class="row"> {% for storage in storage.all %} <a class="text-light" href="{% url 'depot:detailstorage' storage.store_id %}"> <div class="col-md-4"> <div class="card text-white bg-dark mb-3" style="max-width: 18rem;"> <!--div class="card-header">{{ storage.store_name }}</div--> <div class="card-body" style=""> <h5 class="card-title text-center">{{ storage.store_name }}</h5> <img class="card-img-top p-3" src="{{ storage.icon_desc.icon.url }}" /></a> <p class="card-text" style = "font-size:0.7em;">{{ storage.address_1 }} {{ storage.address_2 }} {{ storage.city }} {{ storage.region }} {{ storage.zip }} {{ storage.country }}</p> </div> … -
Uploading and using static (for Django project) to AWS S3
Thanks for taking the time to read this. My issue is simple. I was able to setup the collectstatic function to upload static to AWS S3, but screwed up a little. I have been making some changes and now, my website is not using the correct url to load the css files. So my initial code moved the static to S3 bucket, folder 'static' and referenced it at this url: https://{project}.s3.amazonaws.com/static/css/bootstrap.min.css Now, after some of the changes I have made it references the same address, but without the 'static' folder: https://{project}.amazonaws.com/css/bootstrap.min.css Same thing happens to collectstatic function. Instead of loading all the static to the 'static' folder it loads everything to the root of the bucket. Here is my settings file: settings.py AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static/'), ] STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATIC_URL = "https://%s/static/" % (AWS_S3_CUSTOM_DOMAIN) MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' MEDIA_URL = 'https://%s/media/' % (AWS_S3_CUSTOM_DOMAIN) Thanks for all the help in advance! I really appreciate the community and support. Best, Rasul Kireev -
I have python syntax error in django project
first, i am beginner of django and python i want to make sign up and login service but i have python syntax error I use python 3.7.3 from django.shortcuts import render from django.contrib.auth.models import User from django.contrib import auth def signup(request): if request.method == "POST" : if request.POST["password1"] == request.POST["password2"] : user = User.objects.create_user{ username=request.POST["username"], password = request.POST["password"] if user is not None: auth.login(request,user) return redirect['home'] else: return render(request, 'login.html', {'error': 'username or password is incorrect'}) else: return render(request,'login.html') } in line 8, (user = User.objects.create_user) i have syntax error help me! -
NoReverseMatch at /config/list_enseignant/
I try to list instances of enseignant but I have the raised exception Reverse for 'dfi' with arguments '(14,)' not found. 1 pattern(s) tried: ['config/ajoutdfi/$'] I don't know very well what to do if i delete all the instances of dfi I'll get list of enseignant. models.py class Enseignant(Personne): type_enseignant=models.CharField("Type d'enseignant",max_length=75, choices=(("misssionnaire", "Missionnaire"),("permanent", "Permanent"),("vacataire", "Vacataire") ),default='permanent' ) departement_enseignant=models.ForeignKey("Departement",max_length=75, verbose_name="Département de tutelle", on_delete=models.CASCADE) poste_enseignant=models.CharField("Poste de l'enseignant", max_length=75, choices=(("enseignant","Enseignant"), ('resp_niv', 'Responsable de Niveau'), ('chef_dpt', "Chef de département"), ("dfi", "DFI")), ) grade_enseignant=models.CharField("Grade de l'enseignant",max_length=75, choices=(('M./Mme','M./Mme'),('Ass','Assistant'), ('Cc','Chargé des Cours'),('Mc', 'Maître de conférences'),('Pr','Professeur')) ) anciennete_grade=models.IntegerField('Ancienneté au grade', validators=[ MinValueValidator(limit_value=0, message="L'ancienneté entrée est négative" ), MaxValueValidator(limit_value=50, message='Ancienneté supérieur à 50') ]) def __str__(self): return "{0} {1}".format(self.nom, self.prenom) class DFI(Enseignant): faculte=models.OneToOneField(Faculte, on_delete=models.CASCADE) views.py class list_enseignant(ListView): model =Enseignant context_object_name = "liste_enseignant" template_name = "configuration/lister_enseignant.html" traceback C:\Program Files\Python37\lib\site-packages\django\core\handlers\exception.py in inner response = get_response(request) ... ▶ Local vars C:\Program Files\Python37\lib\site-packages\django\core\handlers\base.py in _get_response response = self.process_exception_by_middleware(e, request) ... ▶ Local vars C:\Program Files\Python37\lib\site-packages\django\core\handlers\base.py in _get_response response = response.render() ... ▶ Local vars C:\Program Files\Python37\lib\site-packages\django\template\response.py in render self.content = self.rendered_content ... ▶ Local vars C:\Program Files\Python37\lib\site-packages\django\template\response.py in rendered_content content = template.render(context, self._request) ... ▶ Local vars C:\Program Files\Python37\lib\site-packages\django\template\backends\django.py in render return self.template.render(context) ... ▶ Local vars C:\Program Files\Python37\lib\site-packages\django\template\base.py in render return self._render(context) …