Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deferred Model Pattern
My Django-SHOP Website sells Videos so my Videomodel has a deferred foreign key to django-filer, like so: class VideoFile(with_metaclass(deferred.PolymorphicForeignKeyBuilder, models.Model)): file = FilerFileField( on_delete=models.CASCADE ) video = deferred.OneToOneField( Product, on_delete=models.DO_NOTHING ) class Video(AvailableProductMixin, Product): videofile = models.ManyToManyField( 'filer.File', through=VideoFile, verbose_name=_("Video file") ) If I use 'Product' in the VideoFile class it gives me the following error: django.core.exceptions.ImproperlyConfigured: Deferred foreign key 'VideoFile.video' has not been mapped but if I use 'BaseProduct' I get this error: ERRORS: project.VideoFile: (fields.E336) The model is used as an intermediate model by 'project.Video.videofile', but it does not have a foreign key to 'Video' or 'File'. The documentation does not really help me, so does anyone know what the problem is here? -
Why Django does not store relations in a database
An empty Django 3.2 project, and only this content in the model.py file and django admin enabled: from django.db import models class Tag(models.Model): name = models.CharField(max_length=150, verbose_name="Tag Name") def __str__(self): return '{}'.format(self.name) class Post(models.Model): name = models.CharField(max_length=150, verbose_name="Post Name") tags = models.ManyToManyField(Tag, blank=True, related_name='posts') def __str__(self): return '{}'.format(self.name) def save(self, *args, **kwargs): super().save(*args, **kwargs) tags = ['a','b','c','d','e'] for tag in tags: dbtag, created = Tag.objects.get_or_create(name=tag) self.tags.add(dbtag) super().save(*args, **kwargs) print (self.tags.all()) Problem: The code creates tags and saves it to the database. The code creates relations, because print -command prints: <QuerySet [<Tag: a>, <Tag: b>, <Tag: c>, <Tag: d>, <Tag: e>]> But relations does not store it in the database, Why? Am I doing something wrong? -
Django sitemaps causes runtime error on random model
I'm trying to add sitemaps to my Django website using its builtin framework django-sitemaps. I believe I have set up everything correctly according to the (at times hard to follow) documentation, but now when I try to runserver I get the following error: [...snip...] File "E:\Programming\my_project\my_project\urls.py", line 7, in <module> from sitemaps import StaticViewsSitemap File "E:\Programming\my_project\some_app\sitemaps.py", line 2, in <module> from models import Story File "E:\Programming\my_project\some_app\models.py", line 18, in <module> class Category(models.Model): File "E:\Programming\my_project\venv\lib\site-packages\django\db\models\base.py", line 113, in __new__ raise RuntimeError( RuntimeError: Model class models.Category doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. The model in question is part of some_app which most definitely is in INSTALLED_APPS, it has worked for months, I haven't touched it in the slightest, and if I comment out everything that relates to sitemaps it works perfectly as it has until now. The model is simply the first one declared in models.py. I think the error has to do with imports and the right parts of the project not being initialised when the sitemaps are constructed. Here is the project's directory tree with the relevant files: my_project ├ my_project │ ├ ... │ ├ urls.py │ └ sitemaps.py ├ some_app │ ├ … -
How to set success url as the previous page after updating an instance in django
I am trying to redirect the user to the previous page after they have updated an instance in the Model Class. So, here is the view for the update: class ClassStatusDetailView(OrganisorAndLoginRequiredMixin, generic.UpdateView): model = Class template_name = "agents/class_status_detail.html" context_object_name = "class" fields = ['status'] def get_success_url(self): return reverse("agents:agent-list") Right now, as you can see, the get_success_url is set to "agents:agent-list", which is not the previous page. Also, here is the template for the update view in case you need it: {% extends "base.html" %} {% load tailwind_filters %} {% block content %} <div class="max-w-lg mx-auto"> <a class="hover:text-blue-500" href="#">Something</a> <div class="py-5 border-t border-gray-200"> <h1 class="text-4xl text-gray-800">{{ class.student }}</h1> </div> <form method="post" class="mt-5"> {% csrf_token %} {{ form|crispy }} <button type='submit' class="w-full text-white bg-blue-500 hover:bg-blue-600 px-3 py-2 rounded-md"> Update </button> </form> </div> {% endblock content %} However, there is a catch. The previous page I want to return to is a function view with a primary key. So, not only do I have to go back to this function view, but I also have to go to the correct primary key. Please tell me if you guys need any other information. Thank you! -
django-elasticsearch-dsl: how to search across multiple documents?
I have several ElasticSearch documents in Django describing each a different type of object: 'MovieDoc,' 'CartoonDoc,' etc. For now on, I can search across every such document individually: document = MovieDoc results = document.search().query('some phrase') But what if I want to search across all documents at once and get the results altogether sorted by relevance (i.e. not searching every individual document and merging thereafter)? I have tried something like this based on the documentation of elasticsearch-dsl, but this did not yield any results: from elasticsearch_dsl import Search results = Search(index=['movie_docs', 'cartoon_docs']).query('some phrase') -
how to create an API for registering tenants in django-tenant?
I'm using django-tenants with a decoupled front end. Everything works for per-tenant apps, but I struggle to figure out to make an api for registering of tenants (and anything else from django-tenants). Obviously I'm lost about serializers,too. For per-tenant user registration, I extend BaseUserManager from django.contrib.auth.base_user. This UserManager handles creating users. So, I would expect that django-tenant would have something like TenantManager, but django-tenant docs don't have documentation on that and I can't find it in code. What django-tenants does have is custom user commands like create_tenant and create_tenant_superuser, which could be useful since in django you can access any management command like this: from django.core.management import call_command call_command('my_command', 'foo', bar='baz') But django-tenants does not have the docs on that either. It seems to me that they're defined here but the code is too complex for me, i don't know how to extent it in my app. -
why does it urlpatterns give me page error?
I have the following in my urls: urlpatterns = [ path('admin/', admin.site.urls), # path('login/', views.login_user), # path('login/submit', views.submit_login), # path('logout/', views.logout_user), # path('', RedirectView.as_view(url='index/all')), path('', views.index), path('index/all/', views.listar_all), path('index/salgados/', views.listar_salgados), path('index/esfirras/', views.listar_esfirras), path('index/pizzas/', views.listar_pizzas), path('index', views.submit), path('submit/', views.submit), path('index/all/submit/', views.submit), ] I have the following in my view: def index(request): print(request.POST) # if request.POST: #Selecionar da tabela apenas os salgados ativos salgados = Salgado.objects.filter(active=True) return render(request, 'index.html', {"salgados":salgados}) def listar_all(request): print(request.POST) # if request.POST: #Selecionar da tabela apenas os salgados ativos salgados = Salgado.objects.filter(active=True) # return render(request, 'index/', {"salgados":salgados}) return render(request, 'index.html', {"salgados":salgados}) def listar_salgados(request): print(request.POST) # if request.POST: #Selecionar da tabela apenas os salgados ativos salgados = Salgado.objects.filter(categoria='Salgados',active=True) return render(request, 'index.html', {"salgados":salgados}) def listar_esfirras(request): print(request.POST) # if request.POST: #Selecionar da tabela apenas os salgados ativos salgados = Salgado.objects.filter(categoria='Esfirras',active=True) return render(request, 'index.html', {"salgados":salgados}) def listar_pizzas(request): print(request.POST) # if request.POST: #Selecionar da tabela apenas os salgados ativos salgados = Salgado.objects.filter(categoria='Pizzas',active=True) return render(request, 'index.html', {"salgados":salgados}) @csrf_protect def submit(request): print(request.POST) if request.POST: # return render(request, 'submit.html', {"salgados":salgados}) # return render(request, '/submit/', {"salgados":salgados}) return redirect('/') The default view loads fine. The listar_pizzas in view works fine but when I click submit button it is giving me error like. Page not found (404) Request Method: … -
Django: Check Number of Rows in one model to be less than or equal to value in another model and one field value restricts other field
I have two models (tables) Power_Sources +---------+-------------+--------------------+------------+ | Vehicle | PowerSource | PowerSourceCurrent | NoOfPhases | +---------+-------------+--------------------+------------+ | Lima | Bus | AC | 3 | | Lima | Bus | DC | 1 | +---------+-------------+--------------------+------------+ Power_Sources_Phases +---------+-------------+-------+ | Vehicle | PowerSource | Phase | +---------+-------------+-------+ | Lima | Bus | A | | Lima | Bus | B | | Lima | Bus | C | +---------+-------------+-------+ How do I do the following in the model: Number of rows in Power_Sources_Phases does not exceed Power_Sources.NoOfPhases on (Vehicle and PowerSource) If Power_Sources.PowerSourceCurrent = DC, Power_Sources.NoOfPhases = 1 I'm using Django 3.2 -
Creating Draftail entity with additional data
I've been using Wagtail to create a website with additional text annotations. The user flow is that there is some highlighted text in a paragraph, which when clicked shows an annotation off to one side. The expected HTML result is: A sentence with <span class='link'>A link<span class='hidden-text'>Hidden text</span></span> I would like to achieve this with a single item on the draftail menu, with a UI similar to the URL creator- the user selects the text, and adds the annotation text. I have followed the instructions on https://docs.wagtail.io/en/stable/advanced_topics/customisation/extending_draftail.html to create a new inline style which produces the link, however I can't then add the hidden-text: # 1. Use the register_rich_text_features hook. @hooks.register('register_rich_text_features') def register_mark_feature(features): """ Registering the `mark` feature, which uses the `MARK` Draft.js inline style type, and is stored as HTML with a `<mark>` tag. """ feature_name = 'mark' type_ = 'SAMPLE' tag = 'sample' # 2. Configure how Draftail handles the feature in its toolbar. control = { 'type': type_, 'label': '?', 'description': 'Hint link', } # 3. Call register_editor_plugin to register the configuration for Draftail. features.register_editor_plugin( 'draftail', feature_name, draftail_features.InlineStyleFeature(control) ) # 4.configure the content transform from the DB to the editor and back. db_conversion = { 'from_database_format': {tag: … -
How to make tests for react & django web-application
Is there a specific way to make tests if you are using Django with react? or do I just test them separately? Is there any open source web site on GitHub/gitlab using react and Django as backend that I can use as reference? (I want to look at real code not just example codes) -
NameError: name 'Class' is not defined, How to access in a class it same name in Django?
models.py file that contain the Category model with name, description parent_category fields class Category(models.Model): """ Categories representation model """ name = models.CharField(max_length=50) description = models.TextField() parent_category = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True) serializers.py file, that container the Category model serializer with all it fields class CategorySerializer(serializers.ModelSerializer): """ product categories model serializer """ parent_category = CategorySerializer() class Meta: """ profile model serializer Meta class """ model = Category fields = ( 'id', 'name', 'description', 'parent_category' ) views.py file, API view to get all available categories with required user authentication class GetCategoriesView(APIView): """ product categories getting view """ permission_classes = (IsAuthenticated,) def get(self, request, *args, **kwargs): """ get request method """ categories = Category.objects.all() serializer = CategorySerializer(categories, many=True, context={'request':request}) return Response(data=serializer.data, status=HTTP_200_OK) Expectected result, Json result with a recursive data from the parent_category field { name:'boy shoes', description:'boy shoes category description' parent_category:{ name:'shoes', description:'shoes category description', parent_category:{ name:'clothes', description:'clothes category description', parent_category: null } } } Error i get, i noticed that i can't access directly the Class inside the same class NameError: name 'CategorySerializer' is not defined How can i solve that?, i think you can help solve that issue Thank you for your attention :) -
How can I display a tuple field from a model to a template in Django?
I'm pretty new to Django here guys so go easy on me please... Let me elaborate on what the title question says. Basically I have this model.... class Meta: verbose_name_plural = 'Digital Media' CATEGORY_CHOICES = ( ('icon_sets', 'Icon Sets'), ('brand_logos', 'Brand Logos'), ('web_banners', 'Web Banners') ) name = models.CharField(max_length=20, choices=CATEGORY_CHOICES) SIZE_CHOICES = ( ('1616', '16 x 16 pixels'), ('3232', '32 x 32 pixels'), ('6464', '64 x 64 pixels'), ('128128', '128 x 128 pixels'), ('256256', '256 x 256 pixels') ) sizes = models.CharField(max_length=20, choices=SIZE_CHOICES) def __str__(self): return self.name and this view ... def product_detail(request, product_id): """ A view to show individual product details """ print_media = Print_Media.objects.all() digital_media = Digital_Media.objects.all() product = get_object_or_404(Product, pk=product_id) print(product, print_media, digital_media) context = { 'product': product, 'print_media': print_media, 'digital_media': digital_media, } return render(request, 'products/product_detail.html', context) So "IF" all is ok with the above code, can someone help me to get the field "sizes" from the model onto a template as I'm having trouble doing this on my own - here is what I have tried so far... {% with product.is_print_media as p %} {% if p %} <div class="col-12"> {{ p.sizes }} <p><strong>Size:</strong></p> <select class="form-control rounded-0 w-50" name="product_size" id="id_product_size"> <option value="{{ p.sizes }}"></option> <option value=""></option> … -
How to take user selected longitude and latitude coordinates as form input in Django?
I am making a Django project where I need the user location coordinates as input for my django form . Just to make it more clear , here is roughly how I want my django form to look : //Form First name [input field] last name [input field] username [input field] location : {a google map like map is shown here where user can search the map and pin a location} [the cordinates of the location pinned by the user on the map are stored in the in the input field] password [input field] How can I achieve this ? I tried the GeoDjango library but it requires installation of too many additional softwares ? is there a simple way to achieve what I want ? -
Django dramatiq, dramatiq abort issue with Elasticache Redis
I use dramatiq and django_dramatiq to setup scheduled delayed jobs. In Django, on a model I added on save() the functions needed to schedule a job. I also use dramatiq-abort in order to be able to cancel jobs. My implementation looks like so: models.py class TestModelA() task_id = models.CharField(max_length=50, blank=True, editable=False) def save(self, *args, **kwargs): """ Creates a dramatiq job on save() """ super(Event, self).save(*args, **kwargs) # if the task id exists, it means a scheduled job has been previously set if self.task_id: # dramatiq abort previous job by the task id abort(self.task_id) # create a new job set_task_id = self.setup_dramatiq_job() # save new task_id on db if set_task_id: self.task_id = set_task_id super(Event, self).save(*args, **kwargs) def setup_dramatiq_job(self): now = timezone.now() # schedule a job to run in 1 minute from now eta = now + timedelta(minutes=1) if eta: milli_to_wait = int((eta - now).total_seconds()) * 1000 result = custom_dramatiq_job.send_with_options( args=('some message',), delay=milli_to_wait, ) return result.message_id return None tasks.py @dramatiq.actor def custom_dramatiq_job(message): return message Now all of the above works and if I hit save multiple times on my local environment I can see jobs being "skipped" / aborted. Let's say it has been saved 5 times; 4 jobs will be skipped … -
jquery get not activating view function
I have this jquery funtcion in my django project that returns pk values to my view function in order to print a pdf with the database values. However, it seems that the view funtction is not saving my pdf when using the get function in jquery. why? my template: <script> let getValues2 = () => $("input[name='checkb']:checked").map((i,el) => el.id.trim()).get(); console.log('getValues2 ',getValues2()) $(document).ready(function() { $('.print').on('click', () => { $.get('eprint/ticked/', { marked: getValues2() }); console.log('print: ',getValues2()) }); $('.delete').on('click', () => { $.get('edelete/ticked/', { marked: getValues2() }); console.log('delete: ',getValues2()) }); }); </script> <td id='row1'><button class='print'><i class="bi bi-sim"></i></button> <form> <label><input type="checkbox" id={{l.pk}} name="checkb"></label> <form> urls.py: path('eprint/ticked/',views.eprint,name='eprint'), views.py: def eprint(request): print('eprint') g=request.GET checked=g.getlist('marked[]') print(checked) res=[Concert.objects.get(pk=l) for l in checked] buffer=io.BytesIO() pdf=canvas.Canvas(buffer) pdf.setFont("Helvetica",14) for l in res: pdf.drawString(1,100,l.cname) pdf.drawString(1,100,"test") pdf.showPage() pdf.save() buffer.seek(0) return FileResponse(buffer,as_attachment=True,filename='test.pdf') -
pass any amount to stripe payment
I am trying out stripe payment method. So have created a test account in stripe. Have also created a web app in pythonanywhere where a user can select an amount from. http://singhaidotnish.pythonanywhere.com/products/dennis/ ( WIP ) Need to pass this selected amount to stripe checkout. If you click on button "Next step to supporting barefoot" it will go to stripe checkout. This should show the selected amount. Not Rs 99 as it now shows. For reference have used https://github.com/PrettyPrinted/youtube_video_code, which is helpful. Next step is to pass selected amount. How is it possible ? -
Django - How to manage many messages?
I'm currently searching for a way to properly manage messages I show the user, as a have a lot of them, for example at my views.py: messages.error(request, 'You cannot do this bla bla') I also have in mind to make the site multi-language. So how do you guys solve this? Do you simply setup a messages.py and reference stuff at views.py or is there maybe a more elegeant way that also has multi-langauge implementation in mind? Thanks in advance :) -
the user who have post should only able to edit blog below code correct but is this professional approach
below is my code inside views.py. Here i don't required that also staff should able to edit but what we should do i needed @method_decorator(login_required(login_url='login'), name='dispatch') class PostUpdate(UpdateView): model = Post form_class = PostForm template_name = 'blog/post_form.html' def get_queryset(self): return super(PostUpdate, self).get_queryset().filter(user=self.request.user) def get_success_url(self): return reverse('dashboard') -
Using specified db in Django connection
I'm using Django to do some db query: from django.db import connection def my_custom_sql(self): with connection.cursor() as cursor: cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz]) cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz]) row = cursor.fetchone() return row And below is my db settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'ka_a', 'USER': 'ka_a', 'PASSWORD': 'ka_a', 'HOST': 'xxx', 'PORT': '3306', 'STORAGE_ENGINE': 'INNODB', 'OPTIONS': { 'init_command': "set sql_mode='traditional'", 'charset': 'utf8mb4' } }, 'ka_b': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'ka_b', 'USER': 'ka_b', 'PASSWORD': 'ka_b', 'HOST': 'xxxxx', 'PORT': '3306', 'STORAGE_ENGINE': 'INNODB', }, } KA_B = 'ka_b' How can I select to KA_B in connection? Thanks -
Redirect another url for first time users in django
I am trying to redirect the url for first time users only using django. I can achive this method using DefaultAccountAdapter for below method. In this method I have used last_login - date_joined so I am facing issue while the users delay to login on same date. So I have tried a method while last_login having blank data but I don't know how to set blank of null for the field. Request you to please give your suggestion for this. Note : first time login users redirect tutuorial-page otherwise all users redirect to welcome page. ## adapter.py using time method class AccountAdapter(DefaultAccountAdapter): def get_login_redirect_url(self, request): threshold = 300 #seconds assert request.user.is_authenticated if (request.user.last_login - request.user.date_joined).seconds < threshold: url = 'tutorial-page/' else: url = settings.LOGIN_REDIRECT_URL return resolve_url(url) ## adapter.py using last_login field empty class AccountAdapter(DefaultAccountAdapter): def get_login_redirect_url(self, request): assert request.user.is_authenticated if (request.user.last_login == null): url = 'tutorial-page/' else: url = settings.LOGIN_REDIRECT_URL return resolve_url(url) -
signals post_save called twice after updating data in class base view django
So i've been stack on this problem that everytime I update my stock in orders it called twice for updating I use the class base view built in Django but in models I have a post signal which it removing the stock of the product. I already use the dispatch_uid but it's not working or any solution that I found on internet not working on my problem. here is my class base view for updating: class ItemQtyUpdateClassBaseView(UpdateView): template_name = 'components/update/item.html' form_class = ItemForm def get_context_data(self, **kwargs): kwargs['context_title'] = 'Update Order Qty' return super(ItemQtyUpdateClassBaseView, self).get_context_data(**kwargs) def form_valid(self, form): try: order_item = OrderModel.objects.get(pk = self.kwargs[self.pk_url_kwarg]) fetch_product = ProductsModel.objects.get(product_name = order_item.product_name) print(fetch_product.qty) if fetch_product.dough != None: if int(fetch_product.dough.qty) <= 0: messages.error(self.request, 'Not enough qty to order.') return self.form_invalid(form) if int(fetch_product.qty) <= 0: messages.error(self.request, 'Not enough qty to order.') return self.form_invalid(form) else: self.object = form.save() messages.success(self.request, 'Successfully update qty.') except Exception as e: messages.error(self.request, e) return self.form_invalid(form) return super(ItemQtyUpdateClassBaseView, self).form_valid(form) def form_invalid(self, form): return super().form_invalid(form) def get_queryset(self): return OrderModel.objects.filter(pk = self.kwargs[self.pk_url_kwarg]) def get_success_url(self): return reverse_lazy('core:createorder', kwargs = { 'typeoforder': self.kwargs['typeoforder'] }) and here is my model with signal post_save: class OrderModel(models.Model): date = models.DateField(auto_now = True) invoice_no = models.ForeignKey(InvoiceModel, on_delete = models.CASCADE) product_name = … -
auth_token table created field is showing different time in pgAdmin and my admin module
I have done TokenAuthentication successfully. When I tried to set token expiring I'm wondering that the field "created" in the auth_token table is showing different time in pgAdmin and my admin module. In pgAdmin it is showing correct time and in my admin module date is correct but time is different . Anyone pls help me out . Anyway thanks in advanve -
How to return all values in serializer from a for loop
hello am quite new to python and Django am stuck in a point. i have number of user_id in the list and against of these user_id's am getting some data from the table named My_story_1 now i want to display the whole data that are related to the user_id in the list. but am just getting the last id data when i put the things in the for loop. here is my code ```for i in (list): print("here i am getting the ids from the list",i) story=My_story_1.objects.filter(user_id=i) serializer = Storiesserializer(story,many=True) return JsonResponse(serializer.data,safe=False)``` and the response am getting is "id": 41, "text": "testa", "time": "2021-04-22T09:12:49.040296+02:00", "user_id": "11" }, { "id": 42, "text": "testing", "time": "2021-04-22T09:13:01.337255+02:00", "user_id": "11" }, { "id": 43, "text": "testing", "time": "2021-04-22T10:18:05.886045+02:00", "user_id": "11" } ]``` here its all the response from the lastly looped user_id: 11 so its showing its data. i want to get the data from the loop complete and store somewhere and in last i can return it. please help me in this.! thanks in advance -
Django - How to allow registration only for predefined list of e-mails/usernames
I have a following simple view in my views.py for registration on my django site: def register_user(request): if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user = authenticate(username=username, password=password) login(request, user) messages.succes(request, ('You have registered')) return redirect('home') else: form = UserCreationForm() context = {'form': form} return render(request, 'register.html', context) That approach would allow anyone to register but I want to allow only selected people to be able to register. I have a simple model for my database class EmailList(models.Model): email_addres = models.CharField(max_length=300, blank=True) def __str__(self): return self.email_addres with some e-mail addreses (my site doesn't have usernames, your username is an email addres) and I want to allow registration only for email addresses that are in that database. How would I perform such check? -
Djanggo sass module not found
im getting this error but a few hours ago this was working just fine, when i run the local server im getting this error enter image description here and when i try to python manage.py makemigrations im getting this error enter image description here i tried pip install django_sass but same thing is happening i read somewhere to try migrations and i did but no, nothing im really confused right now any help will really be appreciated thanks in advance