Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i get the username id in th databas?
I would like to know why the username_id didn't registred in the database , when I use : username = models.OneToOneField(User, blank=True, null=True, on_delete=models.CASCADE) I have (username_id= NULL)enter image description here but when I modified it by : username = models.OneToOneField(User,on_delete=models.CASCADE) I have this message : "IntegrityError at /Patformpage (1048, "Column 'username_id' cannot be null"),How can I resolve this problem , I need your help please. Thank you in advance. This is the code of forms.py class PatForm(forms.Form): nom= forms.CharField(widget=forms.TextInput(attrs={'placeholder':'First_name'})) prénom = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Last_name'})) cin = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'CIN'})) sexe = forms.CharField(widget=forms.Select(choices= sexe)) date_de_naissance = forms.DateField(widget=NumberInput(attrs={'type': 'date'})) quartier = forms.CharField(widget=forms.Select(choices= quartiers)) This is the code of models.py class Patient(models.Model): username = models.OneToOneField(User,on_delete=models.CASCADE) nom = models.CharField("Nom ",max_length=30) prénom = models.CharField("Prénom ", max_length=30) cin = models.CharField("C.I.N ", max_length=10) date_de_naissance = models.DateField(null=True, blank=True) sexe = models.CharField(max_length=10, choices=sex_types, default='1') quartier = models.CharField(max_length=20, choices=quartier_types, default='0') def __str__(self): return self.prénom + ' ' + self.nom This is the code of views.py def Patformpage(request): form = PatForm(request.POST) context = { "form": PatForm } if request.method == 'GET': return render(request, 'base_app/inscription-finale-patient.html', context) elif form.is_valid() : newform= Patient(nom=form.cleaned_data['nom'], prénom=form.cleaned_data['prénom'], cin=form.cleaned_data['cin'], date_de_naissance=form.cleaned_data['date_de_naissance'], sexe=form.cleaned_data['sexe'], quartier=form.cleaned_data['quartier']) newform.save() return redirect('accueil') -
Django create ForeignKey object on parents creation
I have a model with a FK relation: class PNotification(models.Model): id = models.AutoField(primary_key=True) #... booleans with default to come class Product(models.Model): notification_object = models.ForeignKey(PNotification, unique=True, on_delete=models.CASCADE) I get an error: You are trying to add a non-nullable field 'notification_object' to product without a default The only way to create a default 'complex' object I found was get_or_create, but if I use this I need to pass an ID, resulting in each product getting the same PNotification. How can I give each Product an individual PNotification, when a Product model is created? -
¿Como Puedo hacer un insert into en DJANGO? [closed]
tengo una tabla llamada T_EXPERIENCIA con llave compuesta ( correxp(PK) y codpers(PFK)), el codpers viene de la tabla empleado , entonces lo que quiero saber es como inserto mis datos utilizando una sentencia INSERT INTO EN Django , porque he intentado insertar con los modelos de Django , sin embargo no me permite repetir el correxp , pero en SQL Sí me permite , como podría hacer? adjunto mis modelos implicados en este caso class TExperiencia(models.Model): correxp = models.IntegerField(primary_key=True) codpers = models.ForeignKey(TEmpleado, models.DO_NOTHING, db_column='codpers', blank=True, null=True) lugartrabajo = models.CharField(max_length=100, blank=True, null=True) destrabajo = models.CharField(max_length=2000, blank=True, null=True) contrato = models.CharField(max_length=400, blank=True, null=True) fecini = models.DateField(blank=True, null=True) fecfin = models.DateField(blank=True, null=True) nromeses = models.IntegerField(blank=True, null=True) nrodias = models.IntegerField(blank=True, null=True) motivoretiro = models.CharField(max_length=30, blank=True, null=True) codprof = models.ForeignKey('TProfesiones', models.DO_NOTHING, db_column='codprof', blank=True, null=True) vigente = models.CharField(max_length=1, blank=True, null=True) class Meta: managed = False db_table = 't_experiencia' class TEmpleado(models.Model): codpersona = models.OneToOneField('TPersona', on_delete=models.CASCADE, db_column='codpersona', primary_key=True) direcc = models.CharField(max_length=100, blank=True, null=True) celular = models.CharField(max_length=33, blank=True, null=True) hobby = models.CharField(max_length=2000, blank=True, null=True) foto = models.BinaryField(blank=True, null=True) fecnac = models.DateField(blank=True, null=True) dni = models.CharField(max_length=20, blank=True, null=True) liccond = models.CharField(max_length=1, blank=True, null=True) feccipvig = models.DateField(blank=True, null=True) nrocip = models.CharField(max_length=10, blank=True, null=True) flgempliea = models.CharField(max_length=1, blank=True, null=True) observac = models.CharField(max_length=300, … -
django postagedb command refresh_from_db results in MemoryError or .DatabaseError: out of memory for query result
I have an influencer object which have many to many field of 20K+ followers. I can read up to 45 influencers one after the other and execute a worker on it followers. It is not happening immediately but after few hours. code: while True: with ThreadPoolExecutor(max_workers=45) as executor: influencers = Influencer.objects.filter( status__in=[ProcessStatus.recorded, ProcessStatus.unfinished, ProcessStatus.in_progress] ) # Process all the influencers. for influencer_obj in influencers: influencer_obj.refresh_from_db() # start the followers filtering process executor.submit(self.update, influencer_obj) exception: return self.cursor.execute(sql, params) django.db.utils.DatabaseError: out of memory for query result I do have a machine with 80GB running the client, while the postage db machine is not leaking memory (using free command). First, where is the memory issue, on the client or on the db server? Second, what can I do to avoid it ? should I release old obj ? -
Resizing Image before converting to Base64 in Django
I'm working on a django application which has a "My Profile" section where users can upload there profile images. I'm storing the images as a base64 code and rendering on the site. This is the code: @login_required def my_profile_edit(request): if request.method == 'POST': form =ProfileEditForm(request.POST or None,request.FILES,instance=request.user) if form.is_valid(): user=form.save(commit =False) user.user_image =form.cleaned_data['user_image'] user.user_image =base64.b64encode(user.user_image.file.read()) user.user_image ='data:image/jpeg;base64,'+ str(user.user_image)[2:-1] user.save() return redirect('my_profile') profile =CustomUser.objects.get(username=request.user) form =ProfileEditForm(instance=profile) return render(request,'profile_edit.html',{'form':form,'profile':profile}) Though it is working fine, I wish to reduce the size/ resize uploaded image first before encoding it into Base64 to improve performance and reduce space. I've tried few things using StringIO/BytesIO but without success. Please let me know the right way of doing so. -
Email temporary password
Hello I am new to django and web programming. I am building a website for my school that allows students to schedule online advising appointments. I need to be able to email students temporary passcodes to their student emails and then validate them on the next page. I have an email form : class EmailForm(forms.Form): student_email = forms.EmailField(max_length = 200, label = 'Mail') def clean_student_email(self): student_email = self.cleaned_data['student_email'] if not student_email.endswith('.edu'): raise ValidationError("Please enter your school email that ends with @edu") return student_email and a login view def login(request): if request.method == 'POST': form = EmailForm(request.POST) if form.is_valid(): student_email = form.cleaned_data['student_email'] random_code = get_random_string() subject = "Temporary Advising Code" message = f'Your temporary code is: \n code: {random_code}' send_mail(subject, message, 'advising email', [student_email]) return HttpResponseRedirect('/enter_code/', {'form' : form}) else: form = EmailForm() return render(request, 'login/login.html', {'form' : form}) Now I am able to generate a random string and send it to the students email but I am wondering if someone can tell me how I can validate that string on the next page. -
django: hide formset field within template
I am trying to hide some fields from a formset. I have learnt how it is easily possible in the view, however that does not make the trick for me because I need to manipulate those values inside of the view. I am wondering how I could have achieve this in the template only or any other method, I have searched online but cannot find something that would not require to manually set each field of the form inside of the template. here is what I have been able to build so far: def New_Sales(request): #context = {} form = modelformset_factory(historical_recent_data, fields=('Id', 'Description','Date','Quantity', 'NetAmount', 'customer_name', 'invoice_number', 'shipping_number')) if request.method == 'GET': formset = form(queryset= historical_recent_data.objects.none()) for i in range(len(formset)): formset[i]['invoice_number'] == formset[0]['invoice_number'] for i in range(len(formset)): formset[i]['shipping_number'] == formset[0]['shipping_number'] print("formset", formset) #blank_form = formset.empty_form elif request.method == 'POST': formset = form(request.POST) #invoice_hidden_form = CreateInvoiceForm(request.POST) #blank_form = formset.empty_form if formset.is_valid(): #request.session['sale'] = formset.cleaned_data for check_form in formset: check_form.save() quantity = check_form.cleaned_data.get('Quantity') id = check_form.cleaned_data.get('Id') update = replenishment.objects.filter(Id = id).update(StockOnHand = F('StockOnHand') - quantity) update2 = Item2.objects.filter(reference = id).update(stock_reel = F('stock_reel') - quantity) request.session['sale'] = formset.cleaned_data #if invoice_hidden_form.is_valid(): #invoice_hidden_form.save() #print('invoice_hidden_form is saved successfully') #request.session['invoice'] = invoice_hidden_form.cleaned_data print("this is formset.cleaned_data in newsale", formset.cleaned_data) … -
How to avoid using a return statement in a for-in loop?
My view below is only going through one iteration cycle and then breaking out the loop. I know that it's probably because of the return statement in this line: return JsonResponse([post.serialize() for post in posts], safe=False) but how can I avoid this? I tried changing the return statement to a print statement instead but then I get a ValueError: The view network.views.followingPosts didn't return an HttpResponse object. It returned None instead. Just before the except statement I tried putting a continue there but this had no effect. I'm not really sure how to fix this. Any ideas? def followingPosts(request, user_username): try: user_profile = get_object_or_404(User, username=user_username) following_users = user_profile.get_following() for person in following_users: posts = Post.objects.filter(creator=person) except Profile.DoesNotExist: return JsonResponse({"error": "No user found."}, status=404) if request.method == "GET": return JsonResponse([post.serialize() for post in posts], safe=False) else: return JsonResponse({ "error": "GET request required." }, status=400) -
How to implement DRYPermissions in Django REST framework?
I have user accounts with defined permissions in a permissions column, which contains a string consisting of comma separated permission labels, e.g."create_users,view_users,edit_users,delete_users,". To check whether a user has the permission to perform a specific action it is only necessary to check the permissions of the rows of the user and all groups the user is a member of because whenever an user or customer or any relevance's from user looses permissions, all corresponding users and groups will be updated, i.e. the corresponding permissions will be removed. How can I structure a Viewset or a model in order to assign the mentioned permissions to 'create', 'view', 'edit' and 'delete' actions by the user? I'm trying to do so to have a single function that can be reused for different API endpoints that have the same permission pattern. I think DRYPermissions is a good way to go ahead with, but I am not quite sure on how to implement it or are there any other permission methods which would help me here. Any inputs would be highly helpful. Thank you for your time. -
How to preserve the element order when saving a django JSONField
I'm writing a small app that saves JSON verified by a schema to a PostgreSQL DB using Django's JSONField class. I am relying on the data to keep nodes in order butJSONField apparently uses PostgreSQL's jsonb type, which reorders the JSON data to increase indexing performance. Is there a way to preserve the order of elements using this method by forcing the json type instead of jsonb? Or should I give up and look into a different database's JSON support? Samples: What I send to the DB to be saved: "Item": { "@id": "blah" "ItemComponent": { "Weapon": { "@blah": "blah" "WeaponFlags": { "@blah": "blah" } } }, "Flags": { "@blah": "blah", } } How it is saved to the Database: "Item": { "@id": "blah" "Flags": { "@blah": "blah", }, "ItemComponent": { "Weapon": { "@blah": "blah" "WeaponFlags": { "@blah": "blah" } } } } -
How to use crispy_forms_tags and RichTextUploadingField each for a different fields in the same form
I have blog where I have a post as a Title and content as the below model.py: class Post(models.Model): title = models.CharField(max_length=100, unique=True) content = RichTextUploadingField(null=True, blank=True) in my views.py there are 2 fields title and content: class PostCreateView(CreateView): model = Post fields = ['title', 'content'] My question is how to use crispy_forms_tags for the title and RichTextUploadingField for the content Here is the template: <form method='post'enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Post</legend> {{ form.media }} {{ form.as_p }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Submit</button> </div> </form> -
Django REST Framework validate date of birth
As part of the end of a login process a user has to enter their date of birth as a validation check. However I'm not clear how to validate the date of birth against a particular user models.py class CustomUser(AbstractUser): date_of_brith = models.DateField() def __str__(self): return self.username serializers class DobSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = ["date_of_birth"] @api_view(["GET", "POST"]) def dob_view(request): """ """ if request.method == 'GET': users = CustomUser.objects.all() serializer = DobSerializer(users) return Response(serializer.data) if request.method == "POST": serializer = DobSerializer(data=request.data) if serializer.is_valid(): return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_401_UNAUTHORIZED) -
Sending values from ReactForm to Django view
I have a react form as follows: <Form role="form"> <FormGroup> <UncontrolledDropdown> <DropdownToggle caret> Select from the list Of New Tests </DropdownToggle> <DropdownMenu> <DropdownItem>2001</DropdownItem> <DropdownItem>2002</DropdownItem> <DropdownItem>2003</DropdownItem> </DropdownMenu> </UncontrolledDropdown> <br></br> <br></br> <Button color="primary">Submit</Button> </FormGroup> </Form> I have the following view in Django: class FormView(APIView): def get(self, request,*args, **kwargs): return Response({"keywords":applyFormScan(2013)}) I am trying to obtain the value 2013 from the react form.I have tried post method but it doesn't work for me. -
django form submit validation error when there are two submit buttons
in this user profile edit form i have two submit button each button appear onclick when you want to change either your name or your bio (events were handled with vuejs) so when i try to submit the form with the first submit button it submits normally but when i do it with the second one it gives an error: The User could not be changed because the data didn't validate. here is my what i have in my views.py and forms.py # forms.py class UserEditForm(UserChangeForm): class Meta: model = User fields = ('profile_pic','full_name','bio') # views.py current_user = User.objects.get(id=pk) user_edit_form = UserEditForm(instance=current_user) if request.method == "POST": user_edit_form = UserEditForm(request.POST, request.FILES, instance=current_user) if user_edit_form.is_valid: user_edit_form.save() in my template: <form name="user_edit_form" action="" method="POST" enctype="multipart/form-data">{% csrf_token %} <p v-if="!showFNinput" class="text-center text-secondary mt-3"><strong @click="showFNinput = true" id="full-name-edit" > {{current_user.full_name}} <i style="font-size: 8px" class="fas text-muted fa-pen"></i></strong></p> <div v-if="showFNinput" class="text-center" > <input class="mt-3 form-control" v-focus type="text" name="full_name" value="{{current_user.full_name}} "> <!-- First submit button --> <button class="btn btn-success mt-3 mb-2" type="submit">Save</button> </div> <p id="bio-edit" v-if="!showBioinput" class="text-muted text-center" @click="showBioinput = true" > {{ current_user.bio }} <i style="font-size: 8px" class="fas text-muted fa-pen"></i></p> <div v-if="showBioinput" class="text-center" > <textarea class="form-control" v-focus name="bio" cols="5" rows="2">{{current_user.bio}}</textarea> <!-- Second submit button --> <button class="btn … -
No such table on django website deployment on Heroku
I was previously facing issues on deploying my django app on Heroku regarding static directories.But now that I have been able to deploy my website after changing settings.py , there is a error being thrown called 'no such table'.Then I went to stackoverflow for solutions but nothing worked.I am adding my settings.py file here which also has the stackoverflow solutions.I have written a if statement for using PostgreSQL as mentioned in a stackoverflow post but that also don't work.You may see that if statement in last line.My requirements.txt is all correct , so no problem in that.Plz help me. from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve(strict=True).parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '^&ahv#0-lkixr5bfk&)=2%$m$y8kg%z3wt_q)-m(&#u#^xu+pu' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['django-blog-sayan.herokuapp.com', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'users.apps.UsersConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'django_project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': … -
Compare set of model instances with their conterparts in DB | Django
I have a question reg. comparing big set of model instances with data in DB. for example I have a model with 5 fields: model Foo(models.model) fields1 = models.Integerfield() fields2 = models.Integerfield() fields3 = models.Integerfield() fields4 = models.Integerfield() fields5 = models.Integerfield() class Meta: unique_together = (‘field1, field2’) and I have 400.000 model Foo entries saved in DB. Also I have 400.000 +/- few instances in memory(in python)of the same model generated from internet CSV file (without pk set). Question is – what is the most efficient way to do following: 1)If instance in python equal to same instance id DB – keep instance in DB. 2)If instance in python not equal to instance in DB – update instance in DB. 3) If instance in python does not coincide to any instances in DB – write it to DB. 4) If no instances in python coincide to particular instance in DB – delete instance from DB. Its should be bulk operations or RAW SQL as sample size is quite big. Thank you. -
Hi, I have a problem with a django app. I want do make personalized pages for users with this url: url/user/id. But something doesn't work
I'm quite new in the programming world and that's my firs real project. Usually I solve my problems just sitting and thinking till my brain burns. But this time I'm really stacked. Maybe is easy but I really didn't find solutions urls.py from django.urls import path from . import views urlpatterns = [ path('profilo/<int:my_id>/', views.profilo, name='profilo') ] views.py def profilo(request, my_id): users = User.objects.get(id=my_id) contex = { "user": users } return render(request, 'profilo/profilo.html', contex) base.html {% load static %} <html> <head> <title>Django Boyz blog</title> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <link href='//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="{% static 'css/blog.css' %}"> </head> <body> <div class="page-header"> {% if user.is_authenticated %} <a href="{% url 'post_new' %}" class="top-menu"><span class="glyphicon glyphicon-plus"></span></a> <p class="top-menu">Ciao {{ user.username }} <small>(<a href="{% url 'logout' %}">Log out</a>)</small></p> <a href="{% url 'profilo' User.id %}" class="top-menu"><span class="glyphicon glyphicon-user"></span></a> {% if user.is_superuser %} <a href="{% url 'numeroposts' %}" class="top-menu"><span class="glyphicon glyphicon-inbox"></span></a> {% endif %} {% else %} <a href="{% url 'login' %}" class="top-menu"><span class="glyphicon glyphicon-lock"></span></a> {% endif %} <h1><a href="/">Django Boyz Blog</a></h1> </div> <div class="content container"> <div class="row"> <div class="col-md-8"> {% block content %} {% endblock %} </div> </div> </div> </body> </html> The error is this: NoReverseMatch at / Reverse for 'profilo' with … -
Is there any way of redirecting user from In-app browser like Instagram to Google Chrome browser using JavaScript or Python in Android?
I'm trying to make my website redirect from Instagram to Google chrome. This is my JavaScript try to redirect url, but it is not working as I thought: if(navigator.userAgent.includes("Instagram")){ window.open('https://www.google.com/','_blank'); } And in python I've tried using webrowser.get("google-chrome").open("https://www.google.co.in/"), but both methods do not work for me! Please help! Thanks in Advance. -
Passing username (and viewing as uneditable in html) in form Django
I have a form where I would like to have a username and production line send along. The thing is that the username should be taken from current logged user (and viewed as uneditable field) but the production line should be selected via dorpdown. It works by somehow since when I click on "User" dropdown it shows only the logged user. views: def order(request): storage = PartNumber.objects.all() username = request.user.username if request.method == 'POST': order_form = OrderForm(username=username, data=request.POST) if order_form.is_valid(): order_form.save() return redirect('order') elif request.method == 'GET': order_form = OrderForm(username=username) return render(request, 'dashboard/order.html', {"form": order_form, "username": username}) forms: class OrderForm(forms.ModelForm): class Meta: model = Order fields = ('end_user_id', 'production_line_id') def __init__(self, *args, **kwargs): username = kwargs.pop('username', None) super(OrderForm, self).__init__(*args, **kwargs) self.fields['end_user_id'].queryset = User.objects.filter(username=username) models: class Order(models.Model): end_user_id = models.ForeignKey(User, on_delete=models.CASCADE) production_line_id = models.OneToOneField(ProductionLine, on_delete=models.CASCADE) date_ordered = models.DateTimeField(auto_now_add=True, null=True) date_completed = models.DateTimeField(auto_now=True, null=True) def __str__(self): return str(self.status) html: {% extends 'dashboard/main.html' %} {% load static %} {% load bootstrap %} {% block content %} <h3>Zamowienie</h3> <br> <!--{{ form|bootstrap }}--> <form role="form" action="" method="post"> {% csrf_token %} <div class="form-group"> <label>Uzytkownik </label> <!--<input class="form-control" placeholder="{{user}}" readonly>--> {{ form.end_user_id }} </div> <br> <div class="form-group"> <label>Linia produkcyjna </label> {{ form.production_line_id }} </div> <br> <div class="text-center"> … -
JavaScript add class not working on Django template
I want to use this: var btns = document.getElementsByClassName("active-btn"); // Loop through the buttons and add the active class to the current/clicked button for (var i = 0; i < btns.length; i++) { btns[i].addEventListener("click", function() { var current = document.getElementsByClassName("active"); // If there's no active class if (current.length > 0) { current[0].className = current[0].className.replace(" active", ""); } console.log(this.className) this.className += " active"; }); } in my base.html to have a navbar that automatically toggles this active class. But this doesn't work the element gets the class but then the page reloads and the class is away again, I think this is because I use it in a Django template. I hope you can help me. The navbar looks like this: <nav class="top-nav"> <ul class="top-nav-list"> <li class="nav-item menu-icon drop-btn"><div class="icon menu-btn" id="menu-btn"><i class="active-btn material-icons">menu</i></div></li> {% if user.is_authenticated %} <div class="menu-items"> <li class="nav-item menu-item"><a class="active-btn dropdown-btn" onclick="logoutDropDown()">{{user}}</a></li> <div class="dropdowns" id="dropdown-item"> <li class="nav-item menu-item2 dropdown-item" ><a href="/account/profile/edit">Bearbeiten</a></li> <li class="nav-item menu-item2 dropdown-item" ><a href="/account/logout">Abmelden</a></li> </div> {% else %} <li class="nav-item menu-item"> <button onclick="openLoginPopUp()" class="active-btn">Login</button> </li> {% endif %} <li class="nav-item menu-item" id="menu-item"><a class="active-btn" href="/ingredients/my">Meine Zutaten</a></li> <li class="nav-item menu-item"><a class="active-btn" href="/recipes/my">Meine Rezepte</a></li> <li class="nav-item menu-item"> <a class="active-btn active" href="/recipes/all">Alle Rezepte</a> </li> </div> <li class="nav-item menu-item … -
Preventing multiple post requests in django
I have a view function, called new_topic: def new_topic(request): if request.method == 'POST': form = TopicForm(request.POST) if form.is_valid(): form.save() return redirect('learning_logs:topics') else: form = TopicForm() return render(request, 'learning_logs/new_topic.html',{'form':form}) And my new_topic.html is this: {% extends 'learning_logs/base.html' %} {% block title %}Topics{% endblock title%} {% block page_header %} <h1 class="display-4">Add a new topic</h1> {% endblock page_header %} {% block content %} <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Add topic"> </form> {% endblock content %} What I want to do is that if a user clicks the Add topic twice by mistake, the page should only recieve 1 post requests, not 2. Which means that the topic the user wants to add should only be added once, not twice. How can I achieve this? -
Type Error: 'bool' object is not callable
I have a profile model and I want to just the owner of the profile can see it and update it . I'm writing my own permission for that but I have that error what should I do?? Type Error: 'bool' object is not callable #views.py class ProfileRetrieveUpdateView (generics.RetrieveUpdateAPIView): queryset = Profile.objects.all() serializer_class = ProfileSerializer permission_classes = (IsOwner,) #permissions class IsOwner(permissions.BasePermission): """ Custom permission to only allow owners of an object to edit it. """ def has_permission(self, request, view): return request.user and request.user.is_authenticated() def has_object_permission(self, request, view, obj): return obj.user == request.user -
Objects are twicely storing into django database when a single object is created. How to fix this unexpected behavier?
Here i am trying to create a single object with youtube data api , everything is working fine except one thing , when i create a single object it automatically create two objects one with proper details and other one is blank, as shown in pictures , before creating object after creating single object I am trying with the following code. view.py class VideoCreateView(CreateView): model = Video form_class = VideoForm template_name = "videos/video_form.html" def form_valid(self, form): video = Video() video.url = form.cleaned_data['url'] parse = urllib.parse.urlparse(video.url) video_id = urllib.parse.parse_qs(parse.query).get('v') if video_id: video.youtube_id =video_id[0] response = requests.get(f'https://youtube.googleapis.com/youtube/v3/videos?part=snippet&id={video_id[0]}&key={YOUTUBE_API_KEY}') json = response.json() items = json["items"] assert len(items) <= 1 if len(items): title = items[0]["snippet"]["title"] video.title = title video.save() else: title = "N/A" return super().form_valid(form) models.py class Video(models.Model): title = models.CharField(max_length=255) url = models.URLField() youtube_id = models.CharField(max_length=255) slug = models.SlugField(blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("videos:video_detail", kwargs={"slug":self.slug}) def video_pre_save_reciever(sender,instance,*args, **kwargs): if not instance.slug: instance.slug = unique_slug_generator(instance) pre_save.connect(video_pre_save_reciever,Video) if more code is require than tell me in comment , i will update my question with that information. -
Django and synced tables
I am looking for a relatively simple implementation to get a synced table into my project. I looked into stuff like: ezTables django-datatable-view django-datatables-view to replace my django-tables2 table. So far I must say all projects seem outdated and/or not maintained. I am looking for some idea which way to head ... maybe creating the django-tables2 table from a json that gets periodically called (like here) or trying to implement datatables.net by myself (maybe like suggested here)? -
'ManyToManyField' object has no attribute '_m2m_reverse_name_cache'
I am using DRF for django post method,i want to be able to refer images as a manytomanyfield but i am getting an error.Here is the code: class Article(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='articles') images = models.ManyToManyField('Article',symmetrical=False,through='ArticleImages',related_name='fodssfsdmaers', blank=True,) class ArticleImages(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) image = models.ImageField(upload_to='images',null=True,blank=True) articlea = models.ForeignKey(Article, on_delete=models.CASCADE,null=True,blank=True) How can i solve it?