Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why cannot vscode trace into the breakpoint in django.setup?
Why cannot vscode trace into the breakpoint in django.setup? [1]: https://i.stack.imgur.com/ZGmhK.png -
How to send firebase Phone Auth SMS to my flutter app users from my Django backend
How to send firebase Phone Auth SMS to my flutter app users from my Django backend. Am already sending notifications from my Django backend using pycfm def send_single_notification(deviceID,title,body): push_service = FCMNotification(api_key="<api-key>") registration_id = deviceID message_title = title message_body = body result = push_service.notify_single_device( registration_id=registration_id, message_title=message_title, message_body=message_body) So now I need also to trigger the phone auth SMS , so that when user register a new account I use a signal to send him the SMS from firebase and I complete the auth process -
Django filter queryset for replacing charactors
I have a customer table with masked phone numbers (944 (543) 3556) stored in it. (field: phone). I want to filter/search the table using phone number without any special charactors. I tried below filter queries and it is not return expecting results. self.queryset = self.queryset.annotate(customer_phone=Value(re.sub('[^0-9]','','123@#'),output_field=models.CharField())) print ('customer_phone:', self.queryset[0].customer_phone) # Output: customer_phone: 123 [Expected result] But when I give field name, it returns following error. self.queryset = self.queryset.annotate(customer_phone=Value(re.sub('[^0-9]','',F('phone')),output_field=models.CharField())) print ('customer_phone:', self.queryset[0].customer_phone) File "/usr/local/lib/python3.6/re.py", line 191, in sub backend_1 | return _compile(pattern, flags).sub(repl, string, count) backend_1 | TypeError: expected string or bytes-like object Is there anyway to filter phone number without considering the special charactors in it? python version: Python 3.6.5 Django==2.0.1 -
ManytoMany relation in Django?
I have two models class Group(models.Model): .... and class User(models.Model): ... group = models.ManyToManyField( Group) have ManyToMany relations What's the best way to prevent delete Group instance if there are some Users with this Group my solution is : def delete(self, request, *args, **kwargs): try: list_ = [] for user in User.objects.all(): for group in user.group.all(): if group.name not in list_: list_.append(group.name) else: continue if Group.objects.get(pk=kwargs['pk']).name in list_: return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED) else: return self.destroy(request, *args, **kwargs) except: raise ValueError("Error") I hope there are much better solution. -
How to remain in my current page after log-in - Django
I am currently learning Django using the Mozilla developer tutorials. I came across this problem of being redirected to homepage during login even after adding the URL parameter next in my template. The logic works fine during logout, but I seems to have a problem during login I do believe it is my login_direct that is causing the problem. Please how do I override the login_redirect. Thanks. Snippet of my code: My settings.py contains this: LOGIN_REDIRECT_URL = '/' And my template contains this: <li><a href="{% url 'logout'%}?next={{request.path}}">Logout</a></li> {% else %} <li><a href="{% url 'login'%}?next={{request.path}}">Login</a></li> I tried removing the login redirect. -
How can I access Django models from an app running in a different docker container?
I have a django app running in a docker container, attached to a mysql container. Everything is defined a docker-compose file. Now I need another filesystem_watcher container running, that will periodically check a directory on the host. When some files appear in this directory, this app needs to create a new instance of a Django model, and save it to the database. The only way I can think of to do this is to: Have a Django container, with the application code Have a container for my filesystem_watcher, which will also have the entire Django app Attach both to the same mysql container My filesystem_watcher app will import the django models, and use them. This works, but in this scenario, both the Django app Dockerfile, and the filesystem_watcher Dockerfile have entries that copy the entire Django app into both containers. If the source code for the Django app changes, both containers need to be rebuilt. Is there a better way to do this without copying the Django app into the filesystem_watcher container? -
Github Checks are failing due to setuptools dependency
Github checks I have searched online and there seems to be some issue with setuptools version but also changed that in build.yml and still they are failing and this is the line added in build.yml pip install --upgrade pip setuptools wheel please refer to this image github check fail -
Django-apscheduler app the database is locked
I have a fresh django installation with django-apscheduler app ( https://github.com/jcass77/django-apscheduler ) Following the django-apscheduler documentation I was able to add some jobs in the database but after a while the django-apscheduler app stop working with the following error: During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\ginyu\.virtualenvs\django-apscheduler-rsfawqf\lib\site-packages\django\db\backends\utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "C:\Users\ginyu\.virtualenvs\django-apscheduler-rsfawqf\lib\site-packages\django\db\backends\sqlite3\base.py", line 477, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: database is locked The database timeout was already increased in django settings but error persists. Beside to migrate to another database backend, what else can I do to fix this issue? -
How create list with forms? Django
I would create forms with fields. Number fields depends of the user. For example we have list to do: To do: .... .... .... +add more How have I create this form? The simple form is: class ListToDoForms(forms.Form): do = forms.CharField() -
Django ChoiceField RadioSelect widget in form, test whitch element selected in template
I have 2 radio buttons in a ChoiceField and I would like to display some parts of the template, depending of witch radio button is selected. Following : form.py class CtdForm(forms.Form): protocol_name = forms.CharField(max_length=100) rb = forms.BooleanField(required=False, label='RB') mr = forms.BooleanField(required=False, label='MR') CHOICES = [('rb' ,'RB'), ('mr', 'MR')] analyse_type = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect) template html ... {{ form.analyse_type }} Here I would like to test which button is selected and display the template depending of the selection something like : {% if form.analyse_type.? == true %} ... I test a lot of syntaxe with form.analyse_type.? like form.analyse_type.field.widget.choices to have each choices in a loop ect. , but I do not found the right one returning the selected radiobutton... Maybe this way is not the right one to do what I want. If you have any idea, solution thank you ;) -
Dynamic raw query (select clause) Django
I'm trying to execute a raw query in Django where I dynamically want to pick column names. Eg def func(all=True){ if all: query_parameters = { 'col': '*' } else: query_parameters = { 'col': 'a,b,c' } with connections["redshift"].cursor() as cursor: cursor.execute( "select %(col)s from table limit 2 ;", query_parameters, ) val = dictfetchall(cursor) return val } Django is executing it like. select "*" from table limit 2; so the output is just like select "*" * and in the else case it is executed like select "a,b,c" from table limit 2; so the output is a,b,c How can I run the command so that Django run it like select a , b , c from table limit 2 so that the output is a b c 1 2 3 4 5 6 -
How To Send Multiple Variable In HTTPResponse in Django using Ajax
views.py def contact(request): # return HttpResponse("This Is Contact") # To Render String Use HttpResponse if request.method == "POST": name = request.POST.get('name') print(name) email = request.POST.get('email') print(email) number = request.POST.get('number') print(number) discription = request.POST.get('desc') print(discription) # c1 = Contact(name=name) contact = Contact(name=name,email=email,number=number,desc=discription,date=datetime.today()) # c1.save() contact.save() success = 'User ' + name + 'Created Succesfully' success1 = 'email ' + email + 'Created Succesfully' print(success) print(success1) return HttpResponse(success,success1) # messages.success(request, 'Your Messege Has Been Sent!') return render(request,'contactus.html') # Render Menas It Load The index.html file and send the data of context index.html {% csrf_token %} Write Discription Full Name Phone Number Email address We'll never share your email with anyone else. Submit ` $(document).on('submit','#form-post',function(e){ e.preventDefault(); $.ajax({ type:'POST', url:'contact', data:{ name:$('#name').val(), desc:$('#desc').val(), number:$('#number').val(), email:$('#email').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), }, success:function(data,d1){ $('.rsltt').html(data); $('.r1').html(d1); } }) }) ` I am Newbie I Want To Get Multipe Varible Using Ajxax The First Varible PRint Normally The Second Get Show Only Success How Should I Print Both Varibles? My Main Goals Is To print Data Without Refreshing PAge how to solve this error please help me -
Why on_delete of Django Rest Framework not work as expected on Image and File Fields?
When I delete the parent table using Django rest due to on_delete it deletes the child table also (due to foreign key) but the Image and File content of the child table not deleted. I want to delete those images and Files also..! How to do that..? My tables 1:Group 2:Posts One To Many Relation I delete the Group table as follows: GroupsModel.objects.filter(id=py_data.get('group_id')).delete() GroupsModel : class GroupsModel(models.Model): group_name = models.CharField(max_length=20, unique=True) group_description = models.CharField(max_length=50) group_joining_link = models.CharField(max_length=50, default='', unique=True) user_id = models.ManyToManyField(UserModel, through='UserModelGroupsModel', related_name='u_g') class Meta: db_table = 'groups' GroupPostsModel: class GroupPostsModel(models.Model): post_text = models.CharField(max_length=1000) post_type = models.CharField(max_length=20) image = models.ImageField(blank=True, null=True, upload_to='post_images/') document = models.FileField(blank=True,null=True, upload_to='post_documents/') likes = models.IntegerField(default=0) time_stamp = models.DateTimeField(auto_now=True) group = models.ForeignKey(GroupsModel, on_delete=models.CASCADE) user = models.ForeignKey(UserModel, on_delete=models.CASCADE) class Meta: db_table = 'group_posts' I want to delete image and document file also automatically. -
How can I deploy django with apache2
I have Django project that I need to deploy on a VPS and give it domain and SSL certificate and I did that but I still need the ssl certificate so I found that certbot and It worked on the apache well but when I try it using wsgi.py it does nothing at all so I've searched about how to deploy using apache or nginx and all the tutorials didn't work for me so how can I deploy django project using apache2. -
A Django app to take user uploaded locatio
I want to build a Django app to allow users upload their locations which will later be displayed on a map. I would also like to have a search feature where visitors can search and find those uploaded locations. Any help? -
How do I create a custom Django AllAuth Socialaccount model?
Here is a summary of app I am attempting to create: I want users (who are primarily students) to register in my app using their Google Accounts. The service I am using to manage this creation of accounts is Django-AllAuth. Django-AllAuth has a very limited Social Account Model (it only saves username, email, name and their roles). I want to have further fields that I save in my DB. I want to save my users' Year Group and Favourite Subject. How a user registers on my website: User is redirected to a "Sign in With Google" page. Google will return the following fields: the user's name, Google ID and email. Then, I want to prompt the user to a "Finish registering Account" page. In this page, the user will have to fill out input fields for their Username, Year Group and Favourite Subject I cannot find any solutions for this specific case. My Questions How do I create a custom Social Accounts Model in Django-AllAuth? How do I ask users to fill out another Finishing Registering Form? I am aware that you can redirect users to a Finishing Registering Form via this code in the settings.py file. However, this form … -
DRF: Serialization with cross reference table
I have 3 models, the first one contains controller names and their IDs, the second measurements and their IDs and the third has foreign keys to both and is used as a cross reference based on IDs. With the following serializer and view i can have my API return the measurements each controller has. Serializer: class MeasurementsSerializer(serializers.ModelSerializer): # used in stationsMeasurementsInfo view def create(self, validated_data): pass def update(self, instance, validated_data): pass class Meta: model = Measurements fields = ['code', 'measurement', 'unit', 'type'] View: class stationsMeasurementsInfo(generics.ListAPIView): #returns the measurements a station tracks #authentication_classes = (TokenAuthentication,) #permission_classes = (IsAuthenticated,) serializer_class = MeasurementsSerializer def get_queryset(self): source = self.kwargs['sourceName'] name = self.kwargs['stationName'] final = Measurements.objects.filter(microcontrollersmeasurements__microcontroller__name=name) return final def list(self, request, *args, **kwargs): res = super(stationsMeasurementsInfo, self).list(request, *args, **kwargs) res.data = {"source": self.kwargs['sourceName'], "stations": [{ "station": self.kwargs['stationName'], "measurements": res.data } ] } return res The problem is that i cannot actually retrieve the name of the controller, currently i manually insert it in the list which means that i cannot retrieve the measurements of multiple controllers with a single API call. How would i go about fixing this issue? -
Page not found (404) No article found matching the query
#models.py from django.db import models from django.contrib.auth import get_user_model from django.urls import reverse from ckeditor.fields import RichTextField class Article(models.Model): title = models.CharField(max_length=200) body = RichTextField() photo =models.ImageField(upload_to='images/', blank=True) date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE ) def str(self): return self.title def get_absolute_url(self): return reverse('article_detail', args=[str(self.id)]) class Comment(models.Model): article = models.ForeignKey(Article, related_name="comments", on_delete=models.CASCADE) comment = models.TextField(max_length=150) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE ) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.comment def get_absolute_url(self): **return reverse('article_detail', args=[str(self.id)])** class Meta: ordering = ['-date'] -
How to create django dropdown list
I need to create a dropdown list in a datatable field using django in order to display all the countries and enable the user to choose one and get a response. I have tried this code but it does not work. models.py class Datatable(models.Model): COUNTRY_CHOICE = ( ('MA', 'MA'), ('FR', 'FR'), ('US', 'US'), ) Country = models.CharField(blank=True, choices=COUNTRY_CHOICE, max_length=100) datatable.html <th class="Country"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Custumer Country </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> <a class="dropdown-item" href="#MA">MA</a> <a class="dropdown-item" href="#FR">FR</a> <a class="dropdown-item" href="#US">US</a> </div> </th> Any help would be great. Thank you ! -
Proxying shiny-server through Django and nginx
I'm running a docker containerized django app with nginx as a reverse proxy and want to include several shiny apps I've inherited. I want django to sit between shiny-server (which serves the apps) and the client (i.e. NOT reverse proxy certain urls directly to shiny-server). However shiny-server seems to be trying to use some kind of websocket and hence while some elements of the ui render properly, the main files (leaflet maps, plots etc) don't. Instead I get a gray overlay. The console displays some cryptic error messages i.e. Connection closed. Info: {"isTrusted":false}. My nginx configuration is as follows: #Connect to upstream shiny apps server upstream shiny { server shiny:80; } #Connect upstream django server via uWSGI upstream django { server django:8001; } #Required for shiny's WebSockets map $http_upgrade $connection_upgrade { default upgrade; '' close; } server { listen 80; server_name 127.0.0.1; resolver 127.0.0.11; #Production settings #listen 8000; #server_name 195.134.90.182; charset utf-8; client_max_body_size 100M; #Serve django's media (Not Implemented) location /media/ { alias /var/www/media; } location /static/ { alias /var/www/static; } location / { proxy_http_version 1.1; # you need to set this in order to use params below. proxy_pass http://django; proxy_set_header X-forwarded-FOR $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header … -
Problem with updating the value in 1 column in Django database
I have a search model that is saving all search terms that users are typing. Everything is fine except updating total_searches column that I want to update if user will insert exactly the same query. For instance if 3 users will put python in search bar I want to increment value in total_searches column. If the text will be different then create a new "row" in my table. Right now, Django is inserting a new row every time when I search for something and it is just putting 1 in total_searches. How can I fix this? models.py class SearchQueryTracker(models.Model): id = models.AutoField(primary_key=True) author = models.ForeignKey(User, blank=True, null=True, on_delete=models.DO_NOTHING, unique=False) #settings INSTALLED_APPS total_results = models.IntegerField('Search results', default=0) total_searches = models.IntegerField('User searches', default=0) search_term = models.CharField(max_length=1000, blank=True, null=True) searched_on = models.DateTimeField('searched on', default=timezone.now) views.py @login_required def SearchViewFBV(request): query = request.GET.get('q') query_list = request.GET.get('q', None).split() user = User.objects.get(email=request.user.email) find_duplicate_results = SearchQueryTracker.objects.filter(search_term=query).update(total_searches=F('total_searches') + 1) search_tracker = SearchQueryTracker() articles = Article.objects.filter(status=1).order_by('-publish') questions = QA.objects.filter(status=1).order_by('-publish') # combine querysets queryset_chain = chain( articles, questions, ) qs = sorted(queryset_chain, key=lambda instance: instance.pk, reverse=True) count = len(qs) search_tracker.total_results = count search_tracker.total_searches = find_duplicate_results search_tracker.author = user search_tracker.search_term = query search_tracker.save() context = { 'query': query, 'count': count, 'query_list': qs, … -
Django not installing in pipenv on Mac
I'm trying to install Django in pipenv, but it keeps giving me error messages user@users-MacBook-Pro-2 \~ % cd Desktop user@users-MacBook-Pro-2 Desktop % mkdir storefron user@users-MacBook-Pro-2 Desktop % cd storefron user@users-MacBook-Pro-2 storefron % virtualenv install django zsh: command not found: virtualenv user@users-MacBook-Pro-2 storefron % pipenv install django zsh: command not found: pipenv user@users-MacBook-Pro-2 storefron % please any help here user@users-MacBook-Pro-2 storefron % pipenv install django zsh: command not found: pipenv This was suppose to help install Django on the pip virtual environment in the storefron folder created. on the desktop -
Get count of related items and subtract that from attribute in django
I've got three models and I'm trying to simplify my querries a bit. I'm trying to return a list of Course objects that have not been completely registered/paid for. So I need to get a count of the Payment objects, and then see if that is equal to the total available_seats on a Course object. I've got a Payment, Course, and Registration model: class Payment(models.Model): payment = models.ForeignKey(Payment, on_delete=models.PROTECT) registration = models.ForeignKey(Registration, on_delete=models.PROTECT) is_refunded = models.BooleanField(default=False) class Course(models.Model): course = models.ForeignKey(Course, on_delete=models.PROTECT) location = models.ForeignKey(Location, on_delete=models.PROTECT) seat_count = models.IntegerField() class Registration(models.Model): person = models.ForeignKey(Person, on_delete=models.PROTECT) course = models.ForeignKey(Course, on_delete=models.PROTECT) comments = models.CharField(max_length=200, blank=True, null=True) I only want to consider a seat 'taken' if a Payment has been made - so a count of Payment for a given Course is what I'm trying to get. I was trying something like this: payments = ( Payment.objects.filter( registration__course__id=OuterRef("pk"), is_refunded=False ).values("pk") # .annotate( # total_seats_available=F("registration__course__seat_count") # - Count("registration") # ) # .values("total_seats_available") ) courses = ( Course.objects.filter(id__in=course_ids) .prefetch_related( Prefetch( "registration_set", queryset=Registration.objects.prefetch_related( "payment_set" ), ) ) .annotate( paid_seats=Case( When( Exists(payments), then=Count(payments), ), default=None, ), has_available_seats=Case( # No Payment have been recorded When(paid_seats=None, then=Value(True)), # Payment exist and total_seats_available should calc When(paid_seats__gt=0, then=Value(True)), # Default to … -
Django save variable from views to models
I need help with one thing in my django project. I have class games in my views.py which is connected to the path in URLs. The game's class can now take the game_id, player_id, and score values and then use a variable to output them on the result.html page, which works. Instead of listing these values on the page, I need to store these values in a SQL database in Django in a pre-created location using models. models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user_rec = models.ForeignKey(User, on_delete=models.CASCADE) birth_date = models.DateField(null=True, blank=True) game1_score = models.IntegerField(null=True, blank=True) game2_score = models.IntegerField(null=True, blank=True) game3_score = models.IntegerField(null=True, blank=True) class Meta: verbose_name_plural = 'Profile' def __unicode__(self): return u"%s's Subscription Info" % self.user_rec @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() views.py from django.http import HttpResponse from django.contrib.auth.models import User from django.contrib import messages from django.shortcuts import redirect, render from django.contrib.auth import authenticate, login, logout from authentication.models import Profile from rocnikovka import settings from django.core.mail import EmailMessage, send_mail from django.contrib.sites.shortcuts import get_current_site from django.template.loader import render_to_string from django.utils.http import urlsafe_base64_encode,urlsafe_base64_decode from django.utils.encoding import force_bytes, force_str … -
Can we import local csv file data in Django?
i dont to develop a search system in which we are going to import data from csv file which is local file in our computer, i want to import the csv file in django to store it's value in dictionary. but i am not able to import the data in django. here is code and image, and this is view.py file code in which i add csv from unicodedata import name from django.shortcuts import redirect, render from django.http import HttpResponse from django.template import context import csv def index(request): context = {'name':'xyz'} file = open("railway_stations.csv") csvreader = csv.reader(file) rows = [] d = dict() for row in csvreader: rows.append(row) for r in rows: d.update({r[0]:r[1]}) print(r[0]) print(d["Prescot"]) file.close() return render(request, 'home.html',context) and my railway_stations.csv file is in following image \ please please suggest me who to do it. (who to import csv to view.py file) i just try simple import csv to import the csv, i am expecting how to import the csv file in a view.py file so that i am render all the data in html file.also i do it in python in fine way but now i am facing difficulty in django or you can also suggest me good …