Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
pip install unable to build wheel for scrypt and pyethash
I tried to install django-web3-auth with all the commands described in the official documentation pip install django-web3-auth and also tryied from github https://github.com/Bearle/django-web3-auth/archive/master.zip and pip install https://github.com/atereshkin/django-web3-auth/archive/master.zip but I always get the same error Building wheel for scrypt (setup.py) ... error... ERROR: Failed building wheel for scrypt, Building wheel for pyethash (setup.py) ... ERROR: Failed building wheel for pyethash. I am obsessed and desperate now. i'm on windows 10. I've already tried with all the ways I've read in blogs like use --no-cache-dir, but not work. I will love and be eternally grateful to anyone who can help me. i can't sleep with this problem in my head. -
UnboundLocalError: local variable 'faqs' referenced before assignmen
Unbound local error class ServiceHandlerAPI(APIView): def post(self, request, *args, **kwargs): try: link = kwargs.get('link') user = request.data.get('user') user = User.objects.filter(username=user).first() if user: student = user.student student.service_page_views = student.service_page_views + 1 student.save() service = Service.objects.filter(link=link).first() service_user = ServiceUser.objects.filter(user=user).first() if service_user: service_user = True else: service_user = False # testimonials = list(Testimonial.objects.filter(service=service).order_by('-timestamp').values()) testimonials = Testimonial.objects.filter(service=service).order_by('-timestamp') testimonials = TestimonialSerializer(testimonials, many=True) service = serializers.serialize('json', [service, ]) service = service[1: -1] service_name = list(Service.objects.filter(is_available=True).values('heading')) obj = FAQ.objects.all() serializer = FAQSerializer(obj, many=True) faqs = serializer.data if enable_otp: key_id = "rzp_live_6MxRlb7ZCO7XaB" client = razorpay.Client(auth=(key_id, "fGjvMdo8cs7o48pXou5sa3Y5")) else: key_id = "rzp_test_QiGwvmuHqNFHk5" client = razorpay.Client(auth=(key_id, "v4gHikpMnv2DVK0OK6CQ9Ttm")) except Exception as e: print(e) return JsonResponse({'service': service, "service_user": service_user, "faqs": faqs, 'service_name': service_name, 'testimonials': testimonials.data, 'key_id': key_id}) I have imported and included my faqs but still it throws me this error -
How to get a Count based on a subquery?
I am suffering to get a query working despite all I have been trying based on my web search, and I think I need some help before becoming crazy. I have four models: class Series(models.Model): puzzles = models.ManyToManyField(Puzzle, through='SeriesElement', related_name='series') ... class Puzzle(models.Model): puzzles = models.ManyToManyField(Puzzle, through='SeriesElement', related_name='series') ... class SeriesElement(models.Model): puzzle = models.ForeignKey(Puzzle,on_delete=models.CASCADE,verbose_name='Puzzle',) series = models.ForeignKey(Series,on_delete=models.CASCADE,verbose_name='Series',) puzzle_index = models.PositiveIntegerField(verbose_name='Order',default=0,editable=True,) class Play(models.Model): puzzle = models.ForeignKey(Puzzle, on_delete=models.CASCADE, related_name='plays') user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True,null=True, on_delete=models.SET_NULL, related_name='plays') series = models.ForeignKey(Series, blank=True, null=True, on_delete=models.SET_NULL, related_name='plays') puzzle_completed = models.BooleanField(default=None, blank=False, null=False) ... each user can play any puzzle several times, each time creating a Play record. that means that for a given set of (user,series,puzzle) we can have several Play records, some with puzzle_completed = True, some with puzzle_completed = False What I am trying (unsuccesfully) to achieve, is to calculate for each series, through an annotation, the number of puzzles nb_completed_by_user and nb_not_completed_by_user. For nb_completed_by_user, I have something which works in almost all cases (I have one glitch in one of my test that I cannot explain so far): Series.objects.annotate(nb_completed_by_user=Count('puzzles', filter=Q(puzzles__plays__puzzle_completed=True, puzzles__plays__series_id=F('id'),puzzles__plays__user=user), distinct=True)) For nb_not_completed_by_user, I was able to make a query on Puzzle that gives me the good answer, but I am not able … -
How do you properly clone something in Javascript/JQuery?
I'm using .clone() to duplicate a form. I make small changes to the clone and then place it after the last form. As you can see from the screenshot it's mostly working; they look identical. The application (Django/Python) can process the clone as well once I press save. The problem is the calendar widget does not open when clicked (on the clone form). It does open if I click on the widget button for a form that already exists on the page when it first loads (not a clone). But on my clones the date picker does not open. What it should look like after I click on it (instead nothing happens): The cloned html seems to look identical in all the right ways. Existing form: Clone: Is something missing from the cloned html? Or is there something behind the scenes that is not working? I just don't understand what is broken here. JS/JQuery: function cloneMore(selector, prefix,form_class) { var newElement = $(selector).clone(true); var total = $('#id_' + prefix + '-TOTAL_FORMS').val(); newElement.find(':input:not([type=button]):not([type=submit]):not([type=reset])').each(function() { var name = $(this).attr('name').replace('-' + (total-1) + '-', '-' + total + '-'); var id = 'id_' + name; $(this).attr({'name': name, 'id': id}).val('').removeAttr('checked'); }); newElement.find('label').each(function() { var forValue … -
Is there any difference between `(\d+)` and `(\d)+` in Django URLconf? [duplicate]
In Django URLconf I saw two way to match a number: url(r'^grades/(\d+)/$', views.grade_detail), url(r'^grades/(\d)+/$', views.grade_detail), (\d+) and (\d)+, seems both works. is there any difference between them? or difference between (\w+) and (\w)+. -
What does "render" mean in Django?
What does it mean to "render a template" or to "render a form" in Django? Example 1: "Generally a view retrieves data according to the parameters, loads a template and renders the template with the retrieved data. Example 2: "Rendering a form in a template involves nearly the same work as rendering any other kind of object" Would the meaning of render in the above two examples be to "provide" or give"? -
Django best practice models question (from a beginner)
I want to create a model in Django that can describes a garden with rows for plants. Every plant needs some room to grow and i want to describe how many plants would fit in a row - I am a little bit stuck on how to best describe this in Django: from django.db import models from django.contrib.auth.models import User class Plant(models.Model): name = models.CharField('Plantname', max_length=120) size = models.PositiveIntegerField("area around plant in cm") qty = models.PositiveIntegerField("number of plants") color = models.CharField("color of blossom", max_length=20) class Patch(models.Model): FERT = "fertilized" BIO = "biological" METHODS = ((FERT, "Fertilized"), (BIO, "Biological")) type = models.Charfield("kind of patch", max_length=20, choices=METHODS) qty = models.PositiveIntegerField("number of patches") size = models.PositiveIntegerField("length of patch in cm") class task(models.Model): task_id = models.PositiveIntegerField('Task ID') person = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL) patches = models.ManyToManyField(Patch) plants = models.ManyToManyField(Plant) Now I create: two example patches with 300 and 400cm length two example plants with 20 and 15cm length and I want to assign a task to a person that has the number of patches and plants he needs to work on. So when a task is created, I need to: ask for the size and number of the patches Choose the type of plant … -
How to create a pre-save signal in Django?
I have a model which generates a verification token: class VerificationTokenModel(BaseModel): user = models.OneToOneField(User, on_delete=models.PROTECT, related_name='verification_token') verification_token = models.CharField(max_length=100, editable=False, unique=True) token_type = models.CharField(max_length=100, choices=TOKEN_TYPE) expiry_time = models.DateTimeField(default=get_current_time) is_used = models.BooleanField(default=False) Now what I want is that no user can generate another access token within 5 minutes again and user can generate token maximum 10 times a day. How can I achieve this using pre-save signal? -
Implementing Folium inside Django project
I am having a hard time displaying a map inside a django application, and I would like to serve the data from Django models. Is there a way to do this? any help would be appreciated. -
How to use same nested seriaizer for create and listing
I need to use same serializer for create and listing ..... Here is my serializer ..... class OfficeSerializer(ModelSerializer): employees = EmployeeSerializer(many=True, read_only=True) state = StateSerializer(read_only=True) country = CountrySerializer(read_only=True) class Meta: model = Office exclude = ['office_id'] I am using this serializer for listing the office API... Can I able to use the same serializer for Creating ? This is my views.py class OfficeCreateView(CreateAPIView): queryset = Office.objects.order_by('id').all() serializer_class = OfficeSerializer def perform_create(self, serializer): serializer.save() In this case all the fields are saving excluding employees,state,country etc.... class OfficeSerializer(ModelSerializer): employees = EmployeeSerializer(many=True) state = StateSerializer() country = CountrySerializer() class Meta: model = Office exclude = ['office_id'] If I remove read_only field I am getting the following error in Postman { "employees": [ "This field is required." ], "state": [ "This field is required." ], "country": [ "This field is required." ] } How to resolve this -
Django How to customize forms file input
I working with Django & Tailwind CSS project where needs to upload image. I use forms to do this. Now form looks like: image = forms.ImageField(widget=forms.FileInput(attrs={ "class": "bg-nav-blue rounded-xl", } )) But for now it's looks like this one. But for my design I need button How to customize view of this form? -
how to make delete in GenericDeleteView() from Tamplete?
Here is the Model: from django.db import models: class RefugeCamp(models.Model): Camp_Name = models.CharField(max_length=100) Camp_District=models.CharField(max_length=30) Camp_Address =models.CharField(max_length=200) Camp_Block = models.IntegerField() Camp_Population = models.IntegerField() def __str__(self): return str(self.Camp_Name) Here is view : from django.shortcuts import render from django.shortcuts import render, redirect from django.http import HttpResponse from django.views.generic import ListView from django.urls import reverse_lazy from django.db import IntegrityError from django.views.generic import DetailView,UpdateView,DeleteView from django.contrib.auth.decorators import login_required from RefugeCamp.forms import RefugeCampForm from RefugeCamp.models import RefugeCamp # Create your views here. class detail_camp(DetailView): models=RefugeCampForm queryset = RefugeCamp.objects.all() paginate_by = 100 template_name = 'camp/detail.html' class list_camp(ListView): models=RefugeCamp queryset = RefugeCamp.objects.all() paginate_by = 100 template_name = 'camp/camps.html' def add_camp_view(request): if request.method == 'POST': form = RefugeCampForm(request.POST) if form.is_valid(): form.save() pk = form.instance.pk return redirect('camp:detail.html', pk=pk) else: form = RefugeCampForm() context = {'form': form} return render(request, 'camp/addcamp.html', context) class CampDeleteView(DeleteView): # specify the model you want to use model = RefugeCamp template_name = 'camp/delete.html' # can specify success url # url to redirect after sucessfully # deleting object Urls: from django.urls import path from .import views from RefugeCamp.views import list_camp ,detail_camp,CampDeleteView app_name = 'RefugeCamp' urlpatterns = [ path('', views.add_camp_view, name='addcamp'), path('camps/',list_camp.as_view(),name='camps'), path('detail/<int:pk>/', detail_camp.as_view(), name='detail'), path('delete/<int:pk>', CampDeleteView.as_view(), name='camp_delete'), ] now i want to call Delete function from camps.html {% … -
Get Data in a particular Format from serializers in Django
My Models: class Student(models.Model): name = models.CharField(max_length=100) email = models.CharField(max_length=100, unique=True) password = models.CharField(max_length=25) class Subject(models.Model): name = models.CharField(max_length=100) class Student_subject_mapping(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) I'm trying to get all Student_subject_mapping data in the database in a format given below: { "results": [{ "id": 1, "email": "student_1@gmail.com", "subjects": [ { "id": 1, "name": "subject_1" }, { "id": 2, "name": "subject_2" }, ... ] }, My serializers: class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = ('email') class SubjectSerializer(serializers.ModelSerializer): class Meta: model = Subject fields = '__all__' class Student_Mapping_Serializers(serializers.ModelSerializer): class Meta: model = Student_subject_mapping fields = "__all__" How can I achieve data in the above format? -
Open edx , oath2 as provider
I want to redirect to support application from open edx using single sign-on using oauth i.e I will log in to open edx only and while redirecting to support application it shouldn't ask for credentials. Anyone can help me with how to configure or achieve this s=using open edx tutor? Any help is appreciated. -
How to make a web platform discussed in my description? please don't close or down vote ques it becomes difficult for new users
Let me start by what all things are involved: Data in csv file a python script that i have a python file containing a function that user have. On website the user will upload python file. Then the data i have in csv file will be parsed through user's given function which will generate a single Column Dataframe. Then the resultant Dataframe will be parsed through my Python script which will generate an output and this output will be presented to user on website. I am not able to get the approach and technologies involved but this is very important for me to do please help please Any resource or Reference will be helpful pls help Thank you. -
A django url that contains several optional arguments / parameters
While trying to build my first django project, I am stuck at passing values for product filtering. Every feature which has value 1 passed to it, will be an active filter, and others will be 0, i.e. inactive. urls.py: urlpatterns=[ path('women/<str:category>/filter?pricefrom=<int:min>&to=<int:max>&size?s=<int:s>&m=<int:m>&l=<int:l>&xl=<int:xl>&xxl=<int:xxl>&xxxl=<int:xxxl>&color?blue=<int:blue>&red=<int:red>&yellow=<int:yellow>&black=<int:black>&white=<int:white>&green=<int:green>&brown=<int:brown>',views.women_category,name='women category page with filters'), ] views.py: def women_category(request,category,id=None,flag=None,min=None,max=None,s=None,m=None,l=None,xl=None,xxl=None,xxxl=None,blue=None,red=None,yellow=None,black=None,white=None,green=None,brown=None): #product filter logics here I want that the user should be able to use any possible combination of filters, with the filters being: Price: min,max Size: S,M,L,XL,XXL,XXXL color:yellow,blue,green,...etc I don't know how to use Regex in urls, so please help me convert my url into a regex url so that all filter variables are optional to be passed through the fronted. -
How do I change Serverroot directory with Python Path in Django
I have downloaded Apache from Apachelounge. Details : Apache Lounge VS16 Server built: Apr 21 2020 16:23:13 Server's Module Magic Number: 20120211:92 Server loaded: APR 1.7.0, APR-UTIL 1.6.1 Compiled using: APR 1.7.0, APR-UTIL 1.6.1 Architecture: 64-bit httpd.conf: Define SRVROOT "c:/Apache24" ServerRoot "${SRVROOT}" LoadFile d:/python/python37.dll LoadModule wsgi_module d:/lidarlabellingtool_vikram_new2/lidar_venv/lib/site-packages/mod_wsgi/server/mod_wsgi.cp37-win_amd64.pyd WSGIPythonHome d:/lidarlabellingtool_vikram_new2/lidar_venv WSGIPythonPath "D:\Main Project\Lidar-annotation-tool\lidarLabellingTool\lidarProjct" WSGIScriptAlias / "D:\Main Project\Lidar-annotation-tool\lidarLabellingTool\lidarProjct\lidarProjct\wsgi_windows.py" Require all granted Alias /static "D:\Main Project\Lidar-annotation-tool\lidarLabellingTool\lidarProjct\static" Require all granted Require all granted Require all granted Require all granted Require all granted I am facing an issue here. To give you some background here are few details. I am developing my Django application on Windows 10. I am setting my python path in env variable "PATH" (Windows) and WSGIPythonPath in httpd.conf they both are same. There is a file under "D:\Main Project\Lidar-annotation-tool\lidarLabellingTool\lidarProjct\static\scenes" folder which I want to serve it when the request hits the server. But Apache server is taking "c:/Apache2" as base path, I want the Apache server to take WSGIPythonPath or env variable PATH to serve. I am unable to proceed on this. Can somebody help me on this? -
DjangoCMS products and catalog
I want to create DjangoCMS website which shows only a product list and has a filter function. Is there such plugin? Can you suggest me? -
Get queryset of related objects of field from queryset
for example, i have two models. class Store(models.Model): name = models.CharField() class Book(models.Model): store = models.ForiengKey(Store, on_delete=....) I have one queryset of Store objs. I need a queryset of related books with this objs queryset. Please help -
python djnago - automatic log out - inactive user
i want to automatic log out my application when user does not do anything . first user login then user is not active 30 mint. after 30 mint , need to log out automatically how can i done it from client side using python- Django i tried Django-session-time out , using this. https://pypi.org/project/django-session-timeout/ . but its not working in client side. client side always active mode.. how can i log out the inactive user ? -
Handle properly datetimefield in django
Actually I'm facing invalid error whenever I'm using datetime field in django here is my models class Record(models.Model): record_date_time = models.DateTimeField(blank=True) record_time = models.TimeField(blank=True) record_date = models.DateField(blank=True) and forms.py class RecordCreateForm(forms.ModelForm): class Meta: model = Record fields = '__all__' widgets = { 'record_date_time': forms.TextInput(attrs={ 'type': 'datetime-local' }), 'record_time': forms.TextInput(attrs={ 'type': 'time' }), 'record_date': forms.TextInput(attrs={ 'type': 'date' }), } as shown in image, everytings works fine with date field and time field, But I'm facing error with datetime field. I don't know what I'm missing. I need help as soon as possible. -
Django taggit url pattern not working in Production
I was successfully using Django-taggit in development environment but when I have pushed the app to server it has started getting error in url for taggit. Reverse for 'tagged' with arguments '('',)' not found. 1 pattern(s) tried: ['ads\\/tag\\/(?P<slug>[^/]+)$'] My url: path('ads/tag/<slug>', views.filtered_ads, name="tagged") My href: {% for tag in data.tags.all %} <a href="{% url 'furugi:tagged' tag.slug %}" class="mr-1 badge badge-info">{{ tag.name }}</a> {% endfor %} Any thoughts, why is it happening as I am unable to find the problem? -
How to forward naked domain to www with HTTPS [closed]
I'm trying to forward correctly: https://example.com to https://www.example.com without going through 'Your connection is not private' security issue page I don't know why is this happening because my site is secured with HTTPS certificate. If I write this in browser: https://www.example.com will go directly to my secured site without browser's security page popping up. The forward is working but I want to get rid of the security issue. I know is possible because I've seen on other sites. How can I do this? I'm using GoDaddy with the following DNS settings: -
Django redirecting to wrong view
I have an app called 'vocab', which so far contains a CreateView and a ListView. In my project urls.py file, I have the following: urlpatterns = [ path('admin/', admin.site.urls), path('',views.HomePage.as_view(),name='home'), re_path(r"^accounts/", include("accounts.urls", namespace="accounts")), re_path(r"^accounts/", include("django.contrib.auth.urls")), re_path(r"^logout/$", views.LogOutPage.as_view(), name="logout"), re_path(r"^vocab/", include("vocab.urls", namespace="vocab")), ] And then, in my app urls.py file, I have the following: urlpatterns = [ path('list/', views.WordList.as_view(), name="list"), path("home/",views.VocabHome.as_view(),name='home'), path("create/", views.CreateWord.as_view(), name="create"), ] And in my html templates I have links to these views. The home and list views work, but when I click on the 'create' link, it takes me to 'list' instead. In the command line I can see that it is accessing /vocab/list/? instead of /vocab/create/. I know the create view works, because if I type it in manually it goes there. And if I delete all the other views it works as well. So it is as if django cannot find the 'create' view when there are others. I've tried my best to solve this problem by making sure all the paths are unique, and I've tried using regular expressions, but it still doesn't work. Any help would greatly be appreciated! -
Obtain the label from my choices in my views.py - Django
I have a model where one of the fields is the color assigned. class Gateway(models.Model): colors = ( ('0','Black'), ('1','White'), ('2','Blue'), ('3','Red'), ('4','Green'), ('5','Brown'), ('6','Grey'), ('7','Pink'), ('8','Purple'), ('9','Orange'), ('10','Yellow'),('11','Darkolive'), ('12','Lightpink'),('13','Lightblue'), ) gat_id = models.CharField(max_length=16, primary_key=True, unique=True) gat_name = models.CharField(max_length=20, unique=True) gat_lat = models.FloatField() gat_lon = models.FloatField() gat_color = models.CharField(max_length=5, choices=colors, default='Black') My problem is when I want to obtain the model data in my views.py, because I'm doing the following, gateways = Gateway.objects.all() gateways = loads(serializers.serialize('json', gateways)) And this return de color id and I prefer the name of the color. Reading some posts I understand I have to use .choices but I'm not sure where. Can somebdoy help me please? Thank you very much