Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use patterns in the definition of a variable in Django
I am working in Django and I have the following class class Usuario(AbstractBaseUser): username =models.CharField(verbose_name='Nombre de usuario', max_length=45, unique=True) date_join =models.DateTimeField(verbose_name='Fecha de alta', auto_now_add=True) last_login =models.DateTimeField(verbose_name='Última conexión', auto_now=True) es_docente =models.BooleanField(default=False) es_estudiante =models.BooleanField(default=False) es_directivo =models.BooleanField(default=False) es_preceptor =models.BooleanField(default=False) es_tutor =models.BooleanField(default=False) es_superuser =models.BooleanField(default=False) estado =models.BooleanField(default=True) now, I would like to add a function to change the boolean states, if it is possible, by using some kind of pattern. I know that the following code is wrong but I didn't find the correct syntax: def changer(self,var): es_(%var) = not Usuario.es_(%var) where I am marking with %var some kind of usage of the input of the function. For example, I would like to input changer(preceptor) and receive as output that the changing of the boolean field es_preceptor. Thanks in advance! -
I'm making a django webapp and I keep getting pk errors
I keep getting this error even after migrating, making migrations, importing get_object functions, Page not found (404) No storage found matching the query Request Method: GET Request URL: http://127.0.0.1:8000/change-info/1 Raised by: base.views.UpdateInfo Using the URLconf defined in mywallet.urls, Django tried these URL patterns, in this order: admin/ [name='list'] descript/<int:pk>/ [name='descript'] create-bank/ [name='create-bank'] change-info/<int:pk> [name='change-info'] The current path, change-info/1, matched the last one. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. This is my views.py code from django.shortcuts import render from django.views.generic.list import ListView from django.views.generic.detail import DetailView from django.http import HttpResponse from django.views.generic.edit import CreateView, UpdateView from django.urls import reverse_lazy from .models import Storage # Create your views here. class Listings(ListView): model = Storage context_object_name = 'banks' class Information(DetailView): model = Storage template_name = 'base/storage_detail.html' class NewBank(CreateView): model = Storage fields = '__all__' success_url = reverse_lazy('list') class UpdateInfo(UpdateView): model = Storage fields = '__all__' reverse_lazy('list') my urls.py from django.urls import path from .views import Listings, Information, NewBank, UpdateInfo urlpatterns = [ path('', Listings.as_view(), name= 'list'), path('descript/<int:pk>/', Information.as_view(), name='descript'), path('create-bank/', NewBank.as_view(), name='create-bank'), path('change-info/<int:pk>', UpdateInfo.as_view(), name='change-info') ] my models.py from django.db import models … -
Django Rest Framework implement update_or_create when deserializing object
I want to implement update_or_create when deserializing object. I found @K-Moe answer in this question: Django Rest Framework POST Update if existing or create I tried this solution but I got the ValidationError saying that my object already exists: [{'variant_id': [ErrorDetail(string='sku with this variant id already exists.', code='unique')]}, {'variant_id': [ErrorDetail(string='sku with this variant id already exists.', code='unique')]}] Did I miss something? My model class Sku(models.Model): variant_id = models.CharField(primary_key=True, max_length=10, validators=[MinLengthValidator(10)]) name = models.CharField(max_length=255) shop = models.ForeignKey(Shop, related_name='sku', on_delete=models.CASCADE) barcode = models.CharField(max_length=60, null=True, blank=True) price = models.FloatField(null=True, blank=True) def __str__(self): return self.name class Meta: constraints = [ models.UniqueConstraint(fields=['variant_id', 'shop'], name='unique_shop_sku') ] @classmethod def update_or_create(cls, variant_id, shop_id, **kwargs): with transaction.atomic(): return cls.objects.update_or_create(variant_id=variant_id, shop_id=shop_id, defaults=kwargs) My serializers: class SkuSerializer(serializers.ModelSerializer): shop_id = serializers.CharField(source='shop') class Meta: model = Sku fields = ['name', 'shop_id', 'product_id', 'variant_id', 'barcode', 'price'] def create(self, validated_data): sku = Sku.update_or_create( variant_id=validated_data.pop('variant_id'), shop_id=validated_data.pop('shop'), **validated_data ) return sku -
Django NoReverseMatch at /sitemap.xml error for static views
I followed the instruction on django documentation, but I am getting this error when trying to create the sitemap.xml for my app. (also the similar questions on stackoverflow were not describing my case) The html pages that I would like to add to the sitemap are not based on any models, but they have some forms in their footers. (That's why the urls don't contain "as_view()". I have also added INSTALLED_APPS = [ ... 'django.contrib.sites', 'django.contrib.sitemaps', ''' ] to settings.py file. Here are more details: App --> main main/urls.py from django.urls import path from . import views app_name = 'main' urlpatterns = [ path('', views.HomeView, name='homepage'), path('about/', views.AboutView, name='about'), path('contact/', views.Contact, name='contact'), ] main/sitemap.py from django.contrib.sitemaps import Sitemap from django.urls import reverse class StaticViewSitemap(Sitemap): changefreq = 'daily' priority = 0.9 def items(self): return ['homepage','about','contact'] def location(self, item): return reverse(item) Project --> dcohort dcohort/urls.py from argparse import Namespace from django.contrib import admin from django.urls import path, include from django.contrib.sitemaps.views import sitemap from main.sitemaps import StaticViewSitemap from django.conf import settings from django.conf.urls.static import static sitemaps = { 'staticviews': StaticViewSitemap, } urlpatterns = [ path('', include('main.urls', namespace='main')), path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), ] -
<script> tag gets run twice in HTML file
My HTML file is structured the same as any other HTML file. The <head> tag <body> tag and <script> tag all inside the <html> tag. But my <script> tag gets run twice. For example if I add a console.log("hi") inside my <script> it will log in the console: hi hi This is my index.html file: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{% block title %}{% endblock %}</title> <!-- Other links in here --> </head> <body> <!-- Some content in here --> </body> <script> console.log("Hi") // The above command gets executed twice </script> </head> I'm using Django so that is why there are {% load static %} and other things like that, could these maybe be affecting the <script> tag? I'm not quite sure what the problem is, could anyone help? -
Django4.1: Login fails on `localhost`, but succeeds on `127.0.0.1`
Before, i was using SQLite as a database backend, eveything was fine, but i have reached a point where an RDBMS (postgres) was required to setup up proper validations, queries, ... Right after dockerizing postgres, i started seeing this problem. Setup: Django [Not Dockerized] (with ALLOWED_HOSTS = ['*']) DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": "localhost_db", "USER": "root", "PASSWORD": "root", "HOST": "localhost", # set in docker-compose.yml "PORT": 5432, # default postgres port } } Postgres [Dockerized] Redis [Dockerized] CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("localhost", 6378)], }, }, } docker-compose.yaml version: '3.9' services: redis: restart: always image: redis:alpine expose: - 6378 ports: - '6378:6378' volumes: - 'redisdata:/data' command: [ "redis-server", "--bind", "redis", "--port", "6378" ] db: container_name: pg_container image: postgres:alpine restart: always environment: POSTGRES_USER: root POSTGRES_PASSWORD: root POSTGRES_DB: localhost_db ports: - "5432:5432" pgadmin: container_name: pgadmin4_container image: dpage/pgadmin4 restart: always environment: PGADMIN_DEFAULT_EMAIL: root@localhost.com PGADMIN_DEFAULT_PASSWORD: root ports: - "5050:80" volumes: - postgresdata:/var/lib/postgresql/data/ volumes: redisdata: postgresdata: This is my first time seeing this, anyone has ever faced this issue before ? -
i want to display skill data from model in selected tag in django while editing the existing data
i want the existing skills display like placeholder or values in editing tag This is my html skill selecting tag. when a user want to edit his/her details the skills already added should have in the selected tag like a placeholder or a value. The ' sl ' from another context. <div class="form-group"> <label>Skills</label> <span style="color:#ff0000">*</span> <select id="add_skills" name="skills" placeholder="Select Skills" required multiple> <option value="" id="add_skills" disabled selected></option> {% for i in sl %} <option value="{{i.id}}" name="skills">{{i.skill_name}}</option> {% endfor %} </select> </div> this is my model class corporateTrainers(models.Model): Name = models.CharField( max_length=50) Phone_Number = models.IntegerField() Email = models.EmailField(max_length=54 , unique=True) Skill = models.ManyToManyField(Skill) Rate = models.IntegerField() Description = models.TextField(max_length=255) Resume=models.FileField(upload_to="media",null=True,blank=True) def __str__(self): return self.Name its my editing View def editCorporateTrainers(request): if request.method == 'POST': name = request.POST.get('name') email = request.POST.get('email') phone = request.POST.get('phone') rate = request.POST.get('rate') description = request.POST.get('description') skill = request.POST.getlist('skills',[]) description= request.POST.get('description') resume = request.FILES['resume'] trainer = request.POST.get('trainer_Id') resumeobj = FileSystemStorage() resume2 = resumeobj.save(resume.name,resume) var = corporateTrainers.objects.filter(id=trainer) var.update(Name=name,Email=email,Phone_Number = phone , Rate = rate, Description = description, Resume = resume2) vars = corporateTrainers.objects.get(id=trainer) if vars.Skill.exists(): vars.Skill.clear() vars.Skill.add(*skill) messages.success(request,"Record Updated") return redirect('listCorporateTrainers') -
how to i add custom permissions in django rest framework
i wanted to ask can we use model level permissions from django in django rest-framework or do we have to create custom permission differently for django rest-framework. permission = Permission.objects.get(codename = 'is_seller') self.request.user.user_permissions.add(permission) the above code to add permission when a form is submitted is not adding the permission and is showing the error that user_permission does not have a object add() -
Django not showing blank validation message on one of my field
I have a problem with my field. I have two field that have same field and widget. But one of the field didn't show blank validation message. Model: class MagangLetter(models.Model): to=models.CharField(max_length=255) reason=models.CharField(max_length=255) start_date=models.DateField() end_date=models.DateField() Form: class MagangLetterForm(forms.ModelForm): class Meta: model=MagangLetter fields=['to','reason','start_date','end_date'] widgets={ 'to':forms.Textarea(attrs={'class':'form-control','rows':'3','placeholder':'''#example'''}), 'reason':forms.Textarea(attrs={'class':'form-control','rows':'3','placeholder':'''#example'''}), 'start_date':forms.DateInput(attrs={'class':'form-control','type':'date'}), 'end_date':forms.DateInput(attrs={'class':'form-control','type':'date'}) } View class CreateLetterMagang(CreateView): model=MagangLetter form_class=MagangLetterForm template_name_suffix="_create_form" def get_context_data(self, **kwargs): context=super().get_context_data(**kwargs) form:MagangLetter=context['form'] file_template=Template(services.letter.get_html_template('magang.docx')) date=datetime.datetime.now() day=settings.MONTHS[date.strftime('%m')] file_context=Context({ 'letter_number' : '........', 'date_submitted' : f'{date:%d} {day} {date:%Y}', 'to': form['to'], 'name': self.request.user.get_full_name(), 'nim': self.request.user.detail.id_number, 'reason':form['reason'], 'start_date': form['start_date'], 'end_date': form['end_date'], 'nip':'.............', 'dosen':'...............', 'sign': '' }) html=file_template.render(file_context) soup = BeautifulSoup(html, 'html.parser') date_submit=soup.find(string=re.compile("Yogyakarta,")) p=soup.find(string=re.compile("#test")) date_submit.parent.parent['style']='width:15rem;' p.parent['class']='p-0' p=soup.find(string=re.compile("#test")) p.parent['class']='p-0' p=soup.find(string=re.compile("#test")) p.parent['class']='p-0' table=(p.next_element.next_element.next_element) table['class'].append('text-center ms-auto') table['style']='width:fit-content' date_forms=soup.find_all(type='date') for date_form in date_forms: date_form['class'].append('w-25') date_form['style']='min-width:fit-content;' context['docx']=soup.prettify() return context Template: {% block body %} <div class="row content d-block overflow-auto"> <div class="card p-3" style="width:40rem;"> <form method='post'> {% csrf_token %} {{docx|safe}} <input type='submit' class='btn btn-primary' value='Buat Surat'></input> </form> </div> </div> {% endblock body %} validation screenshot to field not showing validation message. reason field showing validation message. How do I show this validation on both field? -
403 Forbidden Error in Django Iframe on Safari Browser
I have a Django Iframe that is working fine on Chrome and Mozilla but in Safari I'm getting the above mentioned error. I think the cookies are not detected because when I checked it was empty and no CSRF tokens were found. I am attaching the screenshots. Error Displayed in browsers console log Browser Cookies is empty. This is my settings.py file: """ Django settings for shopify_django_app project. Generated by 'django-admin startproject' using Django 3.0.2. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os from shopify_app import * from decouple import config # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Make this unique and store it as an environment variable. # Do not share it with anyone or commit it to version control. SECRET_KEY = config('DJANGO_SECRET') DEBUG = int(config('DEBUG')) # SHOPIFY SETTINGS SHOPIFY_API_KEY = config('SHOPIFY_API_KEY') SHOPIFY_API_SECRET = config('SHOPIFY_API_SECRET') SHOPIFY_APP_NAME = config('SHOPIFY_APP_NAME') SHOPIFY_API_VERSION = 'unstable' SHOPIFY_TEST = config('SHOPIFY_TEST') # For the purpose of Shopify Payments INTERNAL_IPS = ('127.0.0.1',) ALLOWED_HOSTS = config('DJANGO_ALLOWED_HOSTS').split(" ") CSP_FRAME_ANCESTORS = ("'self'", 'https://*.myshopify.com') # default source as self CSP_DEFAULT_SRC = ("'self'", "'unsafe-inline'", "'unsafe-eval'", "https://fonts.gstatic.com") # style from our domain … -
how can I output a list in html django?
I have a chat and I need to display a list of people with whom I had correspondence on an html page, i.e. either I wrote to a person or he wrote to me. I wrote the code in views.py , but I don't know how to display an html page. views.py: def send_chat(request): resp = {} User = get_user_model() if request.method == 'POST': post =request.POST u_from = UserModel.objects.get(id=post['user_from']) u_to = UserModel.objects.get(id=post['user_to']) messages = request.user.received.all() pk_list = messages.values_list('user_from__pk',flat=True).distinct() correspondents = get_user_model().objects.filter(pk__in=pk_list) insert = chatMessages(user_from=u_from,user_to=u_to,message=post['message']) try: insert.save() resp['status'] = 'success' except Exception as ex: resp['status'] = 'failed' resp['mesg'] = ex else: resp['status'] = 'failed' return HttpResponse(json.dumps(resp), content_type="application/json") I was trying to get messages in a variable correspondents, but when I try to output this variable through the chatMessages model, it gives an error that there should be ids in correspondents, although I seem to get them anyway my models.py: class chatMessages(models.Model): user_from = models.ForeignKey(User, on_delete=models.CASCADE,related_name="sent") user_to = models.ForeignKey(User, on_delete=models.CASCADE,related_name="received") message = models.TextField() date_created = models.DateTimeField(default=timezone.now) correspondents = models.ForeignKey(User, on_delete=models.CASCADE,related_name="correspondents", null=True) def __str__(self): return self.message my html code: <div class="container" style="height: 75%;"> <div class="card bg-dark h-100 border-light"> <div class="card-body h-100"> <div class="row h-100"> <div class="col-md-4 border-right h-100"> <div class="list-group bg-dark anyClass" id='user-list'> … -
Django: Field 'object_id' expected a number but got 'fe2b1fd4313c'
I am getting this error while trying to save a model from the admin section using Django admin, this is the error Field 'object_id' expected a number but got 'id_b2cbfe2b1fd4313c'.. I am using django shortuuid package https://pypi.org/project/shortuuid/ to create id field in django, and i choose to use it because the inbuild UUID field keeps giving this error Django UUIDField shows 'badly formed hexadecimal UUID string' error? and the id looks like this id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True). What would be the problem witht the short uuid field. Based on this, i quote: If you filter on the ForeignKey, then Django will filter on the primary key of the target object, and that is normally an AutoField, unless you referred to another (unique) column, or defined another primary key as field. But i dont know what the issue might be now Models.py class Channel(models.Model): id = ShortUUIDField( length=16, max_length=40, prefix="id_", alphabet="abcdefg1234", primary_key=True,) full_name = models.CharField(max_length=200) user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True, related_name="channel") Views.py def channel_profile(request, channel_name): channel = Channel.objects.get(id=channel_name, status="active") context = { "channel": channel, } return render(request, "channel/channel.html", context) -
Cannot send message to specific group in Django Channels
I have a websocket that receives a token as a query string. My custom middleware then decodes this token to find the username passed through this token. The current user connecting to the websocket is then subscribed to a group named after their user_id. Let's assume UserA goes through this process initially and they are subscribed to group '1' UserB then connects to the websocket following the same process. At this point I assume there are two groups; one named '1' and another names '2'. Upon UserA triggering the send & receive method in the frontend, I have a consumer function that sends a message to the group with the user_id it receives ('2'). However, when this code runs, I don't seem to be sending a message to any group. I am not getting any error message (I can see the message I want to send being printed on my terminal). However when I open two browsers; one with UserA and the other with UserB, when I connect to the websocket and trigger send/receive I don't see the message I am sending being console logged on either browsers. Here is the code for the consumer class handling the connect, send … -
How to upload pdf format file in Django
I am doing a Django project and my requirement is to upload a file of PDF format only, no other format of files to be shown while selecting files which has to be upload except pdf format file -
How to check for duplicate file contents
I am checking whether a file uploaded already has duplicates of that file. I am using cosine similarity to do the content check. That works fine, but I thinking this way of running a task with for loops of documents that are already accepted against uploaded files that haven't been accepted(processing) yet is not practical. So what would be a more better way to go out this? documents_processing = Document.objects.filter(status='processing') documents = Document.objects.filter(status='accepted') for processing in documents_processing: for document in documents: # If cosine similary > .9: # Stop and update processing document as status=denied, comment=duplicate cosine_similarity = get_cosine_similary(document, processing) if cosine_similarity > 0.9: processing.status = 'denied' processing.comment = 'duplicate' processing.save() else: processing.status = 'accepted' processing.save() What would be the suggestions here for a more efficient code? -
Django 4.1: how to add 'slug_field' to UpdateView for User model from Profile model
I've created the famous Profile model for Django's User model and it has the following fields: [profile_picture, bio, slug] I've registered the Profile model in User model as StackedInLine I've created a view for editing Profile's fields using the slug in the URLconf Now I'm trying to create an UpdateView for the User model in order to change the fields, But it's missing a slug, I tried setting the slug_field to self.profile.slug but it returns a string and not the field. How can I create an UpdateView for the User model using User.profile.slug as the slug in the URLconf? Am I even taking the right approach? models.py: from django.db import models from django.contrib.auth.models import User from django.urls import reverse from .storage import OverwriteStorage def get_upload_path(instance, filename): extension = filename.split('.')[-1] return f'{instance.user.username}/profile_picture.{extension}' class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(blank=True, null=True) profile_picture = models.ImageField(upload_to=get_upload_path, blank=True, storage=OverwriteStorage) slug = models.SlugField(blank=False, null=False) def get_absolute_url(self): return reverse('profile', kwargs={'slug': self.slug}) admin.py: from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.models import User from .models import Profile class ProfileInline(admin.StackedInline): model = Profile can_delete = False verbose_name_plural = 'employee' class UserAdmin(BaseUserAdmin): inlines = (ProfileInline,) admin.site.unregister(User) admin.site.register(User, UserAdmin) views.py: class UserAccountUpdateView(UpdateView): model = User … -
django custom actions interim formpage doesn't submit
Everytime I submit it quits back to model adminpage without executing anything. I'm trying to let there be an interim page for approval purposes. But it either doesn't notice submit or the submit has already happened on page load in other applications. forms.py class ReviewRequestTemplate(forms.Form): emailtemplate = forms.CharField(widget=forms.Textarea, required=True) employers_email = forms.EmailField(required=True) admin.py class EmployerAdmin(TranslationAdmin): list_display = ('name', 'website', 'review_request_sent',) actions = ['request_review',] def request_review(self, request, queryset): context={} RequestTemplateFormset = formset_factory(ReviewRequestTemplate, extra=0) formset = RequestTemplateFormset(initial=[{'emailtemplate': f'Hello {employer.name} Review our service right NOW!','employers_email':employer.email} for employer in queryset]) if 'submit' in request.POST: print('YEES') formset = RequestTemplateFormset(request.POST) if formset.is_valid(): print("formset is valid") else: print('nooo') context['formset'] = formset context['selected_employers'] = queryset return render(request, 'admin/reviewrequest.html', context) admin/reviewrequest.html {%extends "admin/base_site.html" %} {% block content %} <form action="" method="post" name="requestreviewform"> {% csrf_token %} <input type="checkbox" value="check" name="check"> do you want to send? {%for form in formset%} {{form.as_p}} {%endfor%} <input type="submit" name="request_review" value="Send request/s"> </form> {% endblock %} -
How to exclude certain system checks from running on `manage.py migrate`?
I have created a series of checks using Django's System check framework. Some of the checks are used to confirm that fixtures are set up correctly. For example, I have a check that confirms if all users have at least one group. @register(Tag.database) def check_users_have_group(app_configs, **kwargs): errors = [] users = UserModel.objects.all() for user in users: if not user.groups.exists(): message = f'{user} has no permission groups set.' errors.append( Error( message, obj='account', id=f'check_user_{user.id}_permission_groups' ) ) return errors Django's default is to run checks on migration. If I deploy the app without an existing database, then when I run migrate to set up the database the above check will cause a ProgrammingError because the table is not yet created: django.db.utils.ProgrammingError: relation "accounts_account" does not exist How can I exclude this test from running on python manage.py migrate? I want to run this after the migration is complete. -
How to use an absolute path in AJAX with Django?
I use AJAX in my Django project. I would like this AJAX request works for all pages of my project. But it works only for one page and I see that AJAX use the relative path. $.ajax({ type: 'POST', url: {% url 'check_message_st_ajax' %}, headers: {'X-CSRFToken': csrftoken}, data: review_data, dataType: 'json', success: function (response) { const new_messages = JSON.parse(response.mes_list); var number_mes = new_messages.length $('#number_mes').text(new_messages.length); }, }) -
How to use variable in a double underscore method in python / django
I am using the django framework to create a website where i have to do some filtering on my database. I have created a function where you can filter upon any field in the database. I need to use the __gte method to find all records which is greater than or equal to a particular field. I pass the desired field as attribute inside my function. How can i find all records greater than or equal to any field that i pass into my function? def top_percentiles(attribute, web_name, player_id): #filters to find desired player e.g Ronaldo searched_player = PlayerInfo.objects.filter(web_name=web_name, id=player_id) #gets the value of the desired attribute e.g price = 10.0 players_attribute = getattr(searched_player[0], attribute) #filters for all the players with a greater value e.g 10.5, 11.0 players_with_greater_attribute = PlayerInfo.objects.filter(attribure__gte=players_attribute) Error message: Cannot resolve keyword 'attribute' into field. Choices are: assists, bonus, bps... -
How to deal with `Migration is applied before its dependency`
I have been assigned the task to work on project involving react UI and django backend. There are two versions of this app: older version which runs on older versions of react and python (v2) newer version which runs on newer versions of react and python (v3) I have been tasked to move some functionality from older version to newer version and test it with postgres database dump from a live environment running older version. The challenge could be differences in the database schema of newer and older versions. (But, most possibly there wont be much differences if some minor ones.) So I proceeded to take the database dump, attached it to the database running on my laptop and specified its name in my django's settings.ini. But when I started my django app, it gave me error You have 7 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, lab, otherlabs. Run 'python manage.py migrate' to apply them. When I ran python manage.py migrate, it gave me an error: Migration abc.0001_initial is applied before its dependency auth.0011_xyz on database 'default'. So, I deleted record corresponding to abc.0001_initial from django_migrations table and reran … -
django activate link/button if the path startes with `<path>`
I'm building a Django app and I have a link on my navbar that I want to activate it(means add a css class) if the path starts with <base_url>/accounts/ I tried the following and it doesn't work {% url 'accounts:profile' as pro %} {% url 'accounts:setting' as set %} {% url 'accounts:anotherpage' as ano %} This doesn't work {% if request.path == pro or request.path == set or request.path == ano %} active {% endif %} -
Django not auto populating current user foreign key
I'm inserting entries into my database from the front end but the current logged in user foreign key is not populating. It get's entered as null. here is my model: from django.db import models from django.contrib.auth.models import User # Create your models here. class WordsAndPhrases (models.Model): word_or_phrase = models.CharField(max_length=20000) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) added_by = models.ForeignKey(User, null=True, on_delete=models.DO_NOTHING) def __str__(self): return self.word_or_phrase here is my views.py code snippet. def upload(request): if request.method == 'POST': wordOrPhrase = request.POST['word-or-phrase'] currentUser = request.user print(currentUser) newEntry = WordsAndPhrases(word_or_phrase = wordOrPhrase) addedBy = WordsAndPhrases(added_by = currentUser) newEntry.save() return render(request, 'display_words_phrases_app/upload.html') Thanks in advance. -
Why I'm getting name 'request' is not defined in python django 4.1 while rendering a template
name 'request' is not defined Request Method: GET Request URL: http://127.0.0.1:8000/gatepass/gatepass_approve/23/1 Django Version: 4.1 Exception Type: NameError Exception Value: name 'request' is not defined -
How to resolve 2 libraries need different versions of the same dependancy in python
Im trying to install 2 packages: package A requires version <0.16 of package C package B requires version >=0.17 of package C how can such conflict be resolved?