Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Como utilizar ManyToManyField no html para inserção de dados
forms.py from app_teste.models import Diario class FormDiario(forms.ModelForm): class Meta: model = Diario fields = '__all__' models.py from django.db import models class Diario(models.Model): nome = models.CharField('Nome', max_length=50) DiarioDescricao = models.ManyToManyField('Equipamento') class Equipamento(models.Model): descricao = models.CharField('Descrição', max_length=50) views.py from django.shortcuts import render, redirect # Create your views here. from app_teste.forms import FormDiario def index(request): if request.method == "POST": form = FormDiario(request.POST) if form.is_valid(): form.save() return redirect('index') else: form = FormDiario() return render(request, 'index.html', locals()) index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>INICIAL</title> </head> <body> <h1>Pagina Inicial</h1> <div> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Finalizar</button> </form> </div> </body> </html> No template index, quero inserir vários equipamentos, porem sou iniciante e não tenho ideia de como fazer isso, sem sair da pagina. Estou usando ManyToManyField pois na documentação o encontrei e pelo que entendi, da para adicionar vários objetos dentro da mesma tabela. Mas não sei como eu faria no template para poder realizar essa inserção. Me ajudem! Obs: NÃO É NENHUM ERRO, APENAS UMA DUVIDA E UM PEDIDO DE AJUDA! -
How to acces to a model related to a user in DJango
I would like to access to a model related to a user in User. I know that it's possible to get the username or the name of the user using: request.user.get_username() model.py class Profile(models.Model): profile_user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) profile_note = models.CharField(max_length=30,...) Is there any method to take the related model field without a query? Example: request.user.profile.profile_note -
Dynamic rows with jinja template
Project Hi, I'm building a django webapp but i'm having some problems with jinja. I want to create a page were a list of entries can be displayed so something like Django def page(request): entries = Entries.objects.all() context = { 'entries' : entries } return render(request, 'page.html', context) HTML {% for e in entries %} <div class="row"> <div class="title"></div> {% for i in e.list %} <div class="card">i.title</div> {% endfor %} </div> {% endfor %} Problem For each entries i want to display its related list of objects in a row. Problem is that if i have for example 10 elements i'd like to create multiple rows that automatically adapt when user resize the window Is that possible? -
Django add a product to the user automatically
I want to add a product to the user profile, but I can only do it by using a form, and on the template choosing the user from a dropdown menu. What I want to do, is, go to add product ('Añadir vehiculo' in this case), and select the features of said product on the fields, and then I want that product to be automatically added to my profile. As you can see in this image, where it says "Propietario" it's the user(client). https://imgur.com/hWZntVQ And I want to make this: https://imgur.com/VGWUYiv Select every single field but not the "Propietario"(client) one, so It's automatically added to the user who is adding it. But I get these two errors when I change a couple of things, and I can't think of a way to make this work. Errors: "IntegrityError at /perfil-vehiculo-alta NOT NULL constraint failed: webapp_vehiculo.duenio_id" "TypeError at /perfil-vehiculo-alta cannot unpack non-iterable builtin_function_or_method object" and These are the two models that matter: class Usuario(AbstractBaseUser, PermissionsMixin): Departamentos = models.TextChoices('Departamentos', 'Artigas Canelones Cerro_Largo Colonia Durazno Flores Florida Lavalleja Maldonado Montevideo Paysandú Río_Negro Rivera Rocha Salto San_José Soriano Tacuarembó Treinta_y_Tres') nombre = models.CharField(max_length=20, default="") apellido = models.CharField(max_length=20, default="") documento = models.CharField(unique=True, max_length=8, default="") email = … -
How do I adjust my Apache Docker config to only route some URLs to my Docker django instance?
I have Apache, Django, and MySql images set up in my Docker container. Below is my docker-compose.yml file ... version: '3' services: mysql: restart: always image: mysql:5.7 environment: MYSQL_DATABASE: 'maps_data' # So you don't have to use root, but you can if you like MYSQL_USER: 'chicommons' # You can use whatever password you like MYSQL_PASSWORD: 'password' # Password for root access MYSQL_ROOT_PASSWORD: 'password' ports: - "3406:3306" volumes: - my-db:/var/lib/mysql command: ['mysqld', '--character-set-server=utf8mb4', '--collation-server=utf8mb4_unicode_ci'] web: restart: always build: ./web ports: # to access the container from outside - "8000:8000" env_file: .env environment: DEBUG: 'true' command: /usr/local/bin/gunicorn maps.wsgi:application --reload -w 2 -b :8000 volumes: - ./web/:/app depends_on: - mysql apache: restart: always build: ./apache/ ports: - "9090:80" #volumes: # - web-static:/www/static links: - web:web volumes: my-db: Within my Apache configuration, I have set up this virtual host to route traffic to my Django instance ... <VirtualHost *:80> ServerName maps.example.com ProxyPreserveHost On ProxyPass / http://web:8000/ ProxyPassReverse / http://web:8000/ Header set Access-Control-Allow-Origin "*" Header set Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept" </VirtualHost> My question is, how do I alter the above configuration to only send traffic to my Django instance in which the URL begins with the words "data" or "coops"? -
"email": [ "Enter a valid email address."] Django is saying email is not an email
problem: I am trying to serialize an email field using Django Rest Framework, however the server is saying not accepting any email. All emails are greeted with error "Enter a valid email address". Below are my configurations. serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('email', 'password') models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, verbose_name='email address') first_name = models.CharField(max_length=256, verbose_name="First Name", blank=True) last_name = models.CharField(max_length=256, verbose_name="Last Name", blank=True) id = models.UUIDField(primary_key=True, unique=True) data = JSONField(default=default_data, name="device_data") is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] django.core.validators.py @deconstructible class EmailValidator: message = _('Enter a valid email address. Not valid') code = 'invalid' ... domain_whitelist = ['localhost', 'gmail', 'gmail.com', '@gmail.com'] httpie to server http -f POST http://127.0.0.1:8000/reg email="l55@gmail.com", password='pw' response HTTP/1.1 400 Bad Request Allow: POST, OPTIONS Content-Length: 42 Content-Type: application/json Date: Mon, 30 Mar 2020 00:11:14 GMT Server: WSGIServer/0.2 CPython/3.7.3 Vary: Accept, Cookie X-Content-Type-Options: nosniff X-Frame-Options: DENY { "email": [ "Enter a valid email address." ] } Previous effort: I was told to add domains to the domain_whitlist property (which i've done) I have also tried using Django's default user class, but I encountered the same error. Can you help … -
Add a product to the user automatically on django
I want to add a product to the user profile, but I can only do it by using a form, and on the template choosing the user from a dropdown menu. What I want to do, is, go to add product ('Añadir vehiculo' in this case), and select the features of said product on the fields, and then I want that product to be automatically added to my profile. As you can see in this image, where it says "Propietario" it's the user(client). https://imgur.com/hWZntVQ And I want to make this: https://imgur.com/VGWUYiv Select every single field but not the "Propietario"(client) one, so It's automatically added to the user who is adding it. But I get these two errors when I change a couple of things, and I can't think of a way to make this work. Errors: "IntegrityError at /perfil-vehiculo-alta NOT NULL constraint failed: webapp_vehiculo.duenio_id" "TypeError at /perfil-vehiculo-alta cannot unpack non-iterable builtin_function_or_method object" and These are the two models that matter: class Usuario(AbstractBaseUser, PermissionsMixin): Departamentos = models.TextChoices('Departamentos', 'Artigas Canelones Cerro_Largo Colonia Durazno Flores Florida Lavalleja Maldonado Montevideo Paysandú Río_Negro Rivera Rocha Salto San_José Soriano Tacuarembó Treinta_y_Tres') nombre = models.CharField(max_length=20, default="") apellido = models.CharField(max_length=20, default="") documento = models.CharField(unique=True, max_length=8, default="") email = … -
How can I show a dropdown in my form with the title of the objects in the table? Django ModelForm
Hi I've been trying to create a simple app for workflows or binary protocols (yes or no instructions, very helpful sometimes) I have created a simple form with ModelForm: class BlocForm(forms.ModelForm): class Meta: model = Bloc fields = [ 'description', 'loop_child' ] and my model looks like this: class Loopeable(models.Model): protocol = models.ForeignKey(Protocol, on_delete=models.CASCADE, null=True) description = models.TextField() pointing_at = models.IntegerField() class Bloc(models.Model): description = models.TextField() protocol = models.ForeignKey(Protocol, on_delete=models.CASCADE) parent = models.ForeignKey('self',on_delete=models.CASCADE, null=True, blank=True) loop_child = models.ForeignKey(Loopeable, on_delete=models.CASCADE, null=True, blank=True) question = models.BooleanField(default=False) end_bloc = models.BooleanField(default=False) And my problem is that instead of having this loop_chile dropdown list of ugly objects I would like to get the description in the Loopeable Model, is there a way to get some data that is not just "Loopeable Object (id_number)". I didn't add my views.py in order to keep the post short, but I implemented the for by simply doing something like: form = BlocForm(request.POST or None) if form.is_valid(): ...rest of the code If anyone has some ideas I will be grateful!! Thanks... -
Creating dropdown like Django Admin
I hope you're all fine. Thats my first ask here. I am trying to build a dropdown like this: admin button Participant is a model, so it haves some fields like name and institution. How can i add a button like this to my django app? (I don't want to do this on Admin, but in the app) -
Cannot change django auth urls namespace
I'm including all Django auth urls in one go, like this: app_name = "main" urlpatterns = [ ... path("accounts/", include("django.contrib.auth.urls")), ... ] However, if I go to /accounts/password_reset/ and add my email, the email gets sent but it can't resolve the "reset done" url. Error: NoReverseMatch at /accounts/password_reset/ Reverse for 'password_reset_done' not found. 'password_reset_done' is not a valid view function or pattern name. I assume the reason is that it is resolvable at "main:password_reset_done". Then I add a namespace in my url include like this: app_name = "main" urlpatterns = [ ... path("accounts/", include("django.contrib.auth.urls", namespace="main")), ... ] But then I get another error: django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. Which doesn't make sense, as I already have app_name set. -
Django makemigrations tool fails if i change the foreign key / other relationships at models
I have a problem with Djang makemigrations / migrate tool I have a Withdraw model with foreignkey to an Employee table. Everything is working fine models.py from django.contrib.auth.models import User class Withdraw(models.Model): employee_id = models.ForeignKey(Employee, on_delete = models.PROTECT) amount = models.IntegerField(default=0) withdraw_date = models.DateTimeField(default=timezone.now) is_confirmed_by_employer = models.BooleanField(default=False) I want to change it and have user as a foreignkey to user: user = models.ForeignKey(User, on_delete=models.CASCADE) I run makemigrations and I have this errormessage: You are trying to add a non-nullable field 'user' to withdraw without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py If I press 1, then I have the following message, what I dont really get, why shall I put datetime or timezone.now to user?? Select an option: 1 Please enter the default value now, as valid Python The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now Type 'exit' to exit this prompt I tried to delete migrates folder and recreate migration files as was … -
PasswordChangeForm from Django doesnt show on template
I'm tying to make a ChangePasswordForm but it isn't showing on template. The section only prints the description but it doesnt show the form. By the way, Ive been reading about that specific form, and most websites claim it to be implemented by Django, thats why i hadn't put it on forms. I think that might be the mistake. views.py def change_password_view(request): if request.method == 'POST': form = PasswordChangeForm(request.user, request.POST) if form.is_valid(): user = form.save() update_session_auth_hash(request, user) # Important! messages.success(request, 'Contraseña cambiada con éxito') return redirect('profileedit') else: messages.error(request, 'Ha ocurrido un error.') else: form = PasswordChangeForm(request.user) context = { 'form2': form } return render(request, 'profileedit.html', context) template (in case of) <form method="POST" action="#" id="contraForm" name="form2"> {% csrf_token %} <p>Por favor, llena los siguientes campos para cambiar tu contraseña. {{ form2.as_ul }} <button class="btn btn-primary py-1 px-2" type="submit" > Save </button> </p> </form> -
Base64ImageField for Django Nested Serializer
I have a model that looks like this: class ChoiceImage(models.Model): choice = models.OneToOneField(Choice, on_delete=models.CASCADE, null=True) img = models.ImageField(upload_to='some-path/') That points to: class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice = models.CharField(max_length=120) vote_count = models.IntegerField(default=0) When a user submits a Question, it goes through this serializer: class CreateQuestionSerializer(serializers.ModelSerializer): choice_set = CreateChoiceSerializer(many=True) class Meta: model = Question fields = ('user', 'choice_set') def create(self, validated_data): choices_validated_data = validated_data.pop('choice_set') question = Question.objects.create(**validated_data) choices_serializer = self.fields['choice_set'] for choice in choices_validated_data: choice['question'] = question choices_serializer.create(choices_validated_data) return question Then this: class CreateChoiceSerializer(serializers.ModelSerializer): choiceimage = ChoiceImageSerializer(many=False, required=False) class Meta: model = Choice fields = ('choice', 'choiceimage') def create(self, validated_data): image_uploaded = validated_data.get("choiceimage") image_validated_data = validated_data.pop('choiceimage') choice = Choice.objects.create(**validated_data) image_serializer = self.fields['choiceimage'] image_validated_data['choice'] = choice image_serializer.create(image_validated_data) class ChoiceImageSerializer(serializers.ModelSerializer): img = Base64ImageField() class Meta: model = ChoiceImage fields = ('img',) Notice how I have Base64ImageField() as my img. Whenever I submit data in my form, it complains saying no file was submitted. However, I'm submitting a Base64Image I'm not sure why it's complaining about a file when I'm specifying that it'll be a Base64ImageField What am I doing wrong? -
Проблема с файлом wsgi.py (Problem with wsgi.py file)
/ Hi all! Помогите, пожалуйста, настроить файлы wsgi.py для сайта pythonanywhere.com. (Please help set up wsgi.py files for pythonanywhere.com) Лог ошибки, который выводит pythonanywhere. (The error log that pythonanywhere prints) !2020-03-29 21:29:25,095: Error running WSGI application 2020-03-29 21:29:25,095: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. 2020-03-29 21:29:25,095: File "/var/www/relizerel_pythonanywhere_com_wsgi.py", line 22, in 2020-03-29 21:29:25,095: application = get_wsgi_application() !2020-03-29 21:29:25,095: File "/usr/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2020-03-29 21:29:25,095: django.setup(set_prefix=False) !2020-03-29 21:29:25,096: File "/usr/lib/python3.8/site-packages/django/init.py", line 19, in setup 2020-03-29 21:29:25,096: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) !2020-03-29 21:29:25,096: File "/usr/lib/python3.8/site-packages/django/conf/init.py", line 79, in getattr 2020-03-29 21:29:25,096: self._setup(name) !2020-03-29 21:29:25,096: File "/usr/lib/python3.8/site-packages/django/conf/init.py", line 66, in _setup 2020-03-29 21:29:25,096: self._wrapped = Settings(settings_module) !2020-03-29 21:29:25,097: File "/usr/lib/python3.8/site-packages/django/conf/init.py", line 176, in init 2020-03-29 21:29:25,097: raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") Я думаю, что проблема в SECRET_KEY, но во всех файлах он указан. (I think the problem is in SECRET KEY, but in all files it is indicated.) Какие еще данные необходимы, что бы Вам было проще дать ответ? (What other data is needed to make it easier for you to give an answer?) Please, excuse me for using google translator :) -
Is it possible to upload an image directly from django forms?
I wanted to run my Dog vs Cat classifier in my website (in a heroku server) I don't want to consume space in the cloud at the same time don't want to save the uploaded image in the database. This is my code in the views.py file def test_model(request): if request.method == 'POST': form = modelForm(request.POST, request.FILES) if form.is_valid(): form.cleaned_data['label_name'] form.save() inp_img = str(form['test_img'].value()) path = "./media/img/{}".format(inp_img) dest = "./media/img/" resz(path,dest,inp_img) inp = pred_dog_cat().prepare(path) pred,label = pred_dog_cat().prediction(inp) pred = round(pred *100,2) params = {'inpImg':inp_img,'pred':pred,'label':label} return render(request,'dcapp/output.html',params) the modelForm class is in the forms.py from django import forms from .models import * class modelForm(forms.ModelForm): class Meta: model = Test_model fields = ['test_img','label_name'] The models.py file is: class Test_model(models.Model): model_id = models.AutoField(primary_key=True) label_name = models.CharField(max_length=50,default="None") test_img = models.ImageField(upload_to='img/',default="None Selected") output = models.CharField(max_length=50,default="None") def __str__(self): self.str_img = str(self.test_img) return self.str_img I need some guidance about how to upload images from the forms without saving it in the database? And Is it possible to upload it without saving it locally? (as I don't want to consume space in the server) -
How do I create a Django migration to set charset and collation for all existing tables and all future ones?
I'm using Django, Python 3.7 and MySql 5.7. I want to set the default charset and collation for all existing and all future tables to DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci I have already created some migrations, (venv) localhost:maps davea$ ls web/maps/migrations/ 0001_initial.py __init__.py __pycache__ Is there any way I can create such a migration? I'm happy to blow away from database and start from scratch if that's what it takes. -
Unable to save data with custom create serializer django rest_framework
Got AttributeError when attempting to get a value for field note on serializer ProcessStepSerializer2.\nThe serializer field might be named incorrectly and not match any attribute or key on the ProcessStep instance.\nOriginal exception text was: 'ProcessStep' object has no attribute 'note'. My code : model file class ProcessStep(BaseModel): process = models.ForeignKey('Process', on_delete=models.PROTECT) order = models.ForeignKey('Order', on_delete=models.PROTECT) priority = models.FloatField(default=0.0) notes = ArrayField(models.TextField(blank=True), default=list) end_date = models.DateTimeField(default=datetime.now) status = models.CharField(max_length=128, null=True, choices=(('inprogress', 'In Progress'), ('delayed', 'Delayed'), ('completed', 'Completed')) ) in views note = request.data['note'] status = request.data['status'] process = ProcessStep.objects.get(id=slugid) serializer = ProcessStepSerializer2(process, data=request.data, context={'request': request}, partial=True ) // serializer file class NoteSerializer(serializers.Serializer): status=serializers.CharField() type=serializers.CharField() text=serializers.CharField() class ProcessStepSerializer2(serializers.Serializer): note= NoteSerializer() status=serializers.CharField(required=True) user=serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) def update(self, instance, validated_data): user = None request = self.context.get("request") if request and hasattr(request, "user"): user = request.user current_time = datetime.datetime.now(tz=datetime.timezone.utc) note = validated_data['note'] note['time'] = current_time.replace(tzinfo=datetime.timezone.utc).timestamp() * 1000 note['user'] = UserSerializer(request.user).data validated_data['jsondumpednote'] = json.dumps(note) instance.notes.append(validated_data.get('jsondumpednote', instance.notes )) instance.status = validated_data.get('status', instance.status) instance.save() return instance So, it is returning the above error. My doubts: 1. when calling save on serializer in views, if am not passing previous instance than it should create, right? 2. similarly when updating, when object instance is passed, than it should update, right? 3. Does … -
how to take foreign key fields in actual form validation, DJANGO
Thanks for your time: i want to set Validation Error with data that is already written in other modelclass. Models.py class People(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='person') birthday = models.DateField() cpf = models.CharField(max_length=11, validators=[RegexValidator(r'^\d{1,10}$')]) def __str__(self): return '%s' % (self.user) class Pets(models.Model): pessoa = models.ForeignKey(People, on_delete=models.CASCADE) nome = models.CharField(max_length=150) custo = models.DecimalField(max_digits=7, decimal_places=2) tipo = models.SmallIntegerField() def __str__(self): return '%s - %s' % (self.pessoa, self.nome) Forms.py: class PetForm3(forms.ModelForm): #SELECIONAR FORM PELO FORMS.PY field_choices = [ (1, 'CACHORRO'), (2, 'GATO'), (3, 'ANDORINHA') ] nome = forms.CharField(max_length=100) custo = forms.DecimalField(max_digits=7, decimal_places=2) tipo = forms.ChoiceField(choices=field_choices) class Meta: prefix = 'pet' model = Pets fields = ['nome', 'custo', 'tipo'] def clean_tipo(self): data = self.cleaned_data.get("tipo") data_pessoa = self.cleaned_data.get("pessoa") slug = slugify(data_pessoa) if slug.startswith('a'): data == 2 raise forms.ValidationError('nomes com A nao podem ter gatos') return data i got these two models and the Pets is a ManytoOne to People i'd like to take attributes of People like birthday and cpf in the clean_method of PetForm3. and like to get the ''pessoa'', whithout having to display, field from Pets on the clean method either. i'm able to achieve something like that with request.user in views.py but i'd like to get it in clean_method at forms.py -
Traverse multiple foreign keys in Django DetailView
I'm working on a project to record all scores shot at a bunch of archery events. They are shot by many people at many events and many different archery rounds. (A "round" in archery is a particular type of competition. For the sake of simplicity let's say there are two: indoor and outdoor.) Here's a basic ER diagram of the relevant part of my database model: ┌───────────┐ ┌───────────┐ ┌────────────────┐ ┌───────────┐ │ │ ╱│ │╲ │ │╲ │ │ │ Person │──────┼──│ Score │──┼────│ EventRound │──┼─────│ Event │ │ │ ╲│ │╱ │ │╱ │ │ └───────────┘ └───────────┘ └────────────────┘ └───────────┘ ╲│╱ ┼ │ ┌───────────┐ │ │ │ Round │ │ │ └───────────┘ You can see that there are two ManyToMany relationships at work here resolved with two junction tables (EventRound and Score). I'm creating these junction tables manually by specifying the "through" table and "through_fields" in models.py. I've created a PersonDetailView that allows me to access and iterate through all of the scores in the Score table for a specific person. (Thanks to Jaberwocky and his solution at Detailview Object Relations) # views.py class PersonDetailView(DetailView): model = Person queryset = Person.objects.all() template_name = 'person_detail.html' def get_context_data(self, **kwargs): context = super(PersonDetailView, self).get_context_data(**kwargs) … -
How to upload multiple images and sort them? - Django
I am building an application with Django and I am struggling with uploading multiple images to each post. I want the users to be able to easily upload images (up to 7) to each post and also be able to sort them around, in other words, to be able to choose in which order the images will be displayed. If anyone knows how to do this or knows of any good guides/tutorials out there that shows how to do this, please let me know. I would really apprecciate it! Thanks -
django models - how can i create abstract methods
In django abstract classes seem to be posibble by using: class Meta: abstract = True However I do not see how to declare abstract methods/functions within these classes that do not contain any logic like e.g. class AbstractClass(models.Model): def abstractFunction(): class Meta: abstract = True The library abc repectively the notation @abstractmethod doesnt seem to applicable here, or am I wrong? -
Django views.py is not rendering html file?
i am sending an object to backend (django) via ajax "POST" method. in the views.py the code runs but the render statement is not executing. ajax $.ajax({ url: '{% url "chout" %}', data: { 'object': object1, 'csrfmiddlewaretoken':csrf }, method: "POST", dataType: 'json', success: function (data) { alert("success"); } }); views.py return render(request, "mart/checkout.html", {"total": total_price, "final_bill": final_dict}) Everything above return statement runs smoothly but somehow the return line dont run. it is not showing any error or warning either. -
Django Ajax form submitted twice
I am trying to submit a post creation form, however, after I click on my submit button the view is called twice and the post object is created twice upon my Ajax request, I was wondering what Is causing this issue? This is my post_create view: @login_required def post_create(request): data = dict() if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): post = form.save(False) post.author = request.user #post.likes = None post.save() data['form_is_valid'] = True posts = Post.objects.all() data['posts'] = render_to_string('home/posts/home_post.html',{'posts':posts}) else: data['form_is_valid'] = False else: form = PostForm context = { 'form':form } data['html_form'] = render_to_string('home/posts/post_create.html',context,request=request) return JsonResponse(data) This is my post.js for handling Ajax: $(document).ready(function(){ var ShowForm = function(){ var btn = $(this); $.ajax({ url: btn.attr("data-url"), type: 'get', dataType:'json', beforeSend: function(){ $('#modal-post').modal('show'); }, success: function(data){ $('#modal-post .modal-content').html(data.html_form); } }); return false; }; var SaveForm = function(e){ e.preventDefault(); var form = $(this); $.ajax({ url: form.attr('data-url'), data: form.serialize(), type: form.attr('method'), dataType: 'json', success: function(data){ if(data.form_is_valid){ $('#post-list div').html(data.posts); $('#modal-post').modal('hide'); } else { $('#modal-post .modal-content').html(data.html_form) } } }) return false; } //create $('.create-post-btn').click(ShowForm); $('#modal-post').on("submit",".post-create-form",SaveForm) //update $('#post-list').on("click",".show-form-update",ShowForm); $('#modal-post').on("submit",".update-form",SaveForm) //delete $('#post-list').on("click",".show-form-delete",ShowForm); $('#modal-post').on("submit",".delete-form",SaveForm) }); And this is my post model: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField(validators=[MaxLengthValidator(250)]) author = models.ForeignKey(Profile, on_delete=models.CASCADE) date_posted = models.DateTimeField(auto_now_add=True) last_edited= … -
No module named 'registration' in django 2.2.5
I am using django 2.2.5 with python 3.6 i have installed django-registration by adding it to my project's installed apps and then doing a pip install django-registration. All this worked fine but now when i am trying to perform a python mange.py makemigrations am getting this error. I read a lot of solutions online and they don't seem to work, i tried downgrading the django-registration version to 2.4 but then it uninstall django 2.2.5 because it works with django 1, which will cause some other serious problems. here is my installed app section: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'registration', 'wewriteapp', 'crispy_forms', ] Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Ahmed\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Ahmed\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\Users\Ahmed\Anaconda3\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Ahmed\Anaconda3\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\Ahmed\Anaconda3\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\Ahmed\Anaconda3\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'registration' -
Django request.user modification not happening in test
I have a view that is changing a field of request.user: def test(request): request.user.is_provider = False request.user.save() print(request.user.is_provider) return HttpResponse(status=200) Now I am testing the function and I have the following test: class RoleSwitchTests(TestCase): def test_switch_to_customer(self): User = get_user_model() user = User.objects.create_user( username='test', email='test', password='test', first_name='test', last_name='test', is_provider=True, is_admin=False, ) self.client.login(username='test', password='test') response = self.client.post('/test/', follow=True) print(user.is_provider) self.assertEqual(response.status_code, 200) self.assertFalse(user.is_provider) self.assertFalse(user.is_provider) fails here. For some reason, request.user.is_provider is False in test, but in test_switch_to_customer, user.is_provider is True. I know these refer to the same user because they have the same id, so why is the modification not being preserved here?