Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Preventing the user from entering wrong url patterns
How can i prevent the user from entering in url values that might crash my application. For instance cars have an id, so to navigate to a car would be http://127.0.0.1:8000/car/1, and if user enters an id that does not exist then it crashes, how can i prevent this? urlpatterns = [ path('', include('index.urls')), path('cars/', include('car.urls')), path('users/', include('user.urls')), path('admin/', admin.site.urls), ] -
Run local .exe file from firefox linux machine with js page and capture output
I'm trying to execute a local .exe file from the js of my html page in a firefox brower in a linux machine. I Know it's not secure but it will be locally and I have read some options but none of them really fits. I would also like to read the stdout and capture it. I have tried many things, my code right now is the following: var oShell = new ActiveXObject("WScript.shell"); oshell.run("/usr/share/applications/rfid.desktop"); var res = oShell.StdOut.ReadAll; console.log(res); or this: alert("In fun RunExe().."); netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); alert("Done"); var exe = window.Components.classes['@mozilla.org/file/local;1'].createInstance(Components.interfaces.nsILocalFile); exe.initWithPath("{% static '../../rfid-csharp/RFID.exe' %}"); alert("exe"); var run = window.Components.classes['@mozilla.org/process/util;1'].createInstance(Components.interfaces.nsIProcess); run.init(exe); var parameters = [""]; run.run(false, parameters,parameters.length); alert("in function RunBat"); But none of them works first because activeXObject is only for ie and the second the error is: ReferenceError: netscape is not defined Uncaught TypeError: Cannot read property 'classes' of undefined I have also tried creating a desktop.file but I don't know how to execute it from the js either. Thank you very much and sorry for my poor english. -
how to set expire time in django password reset link?
i am using django default password reset functionality and here i want to set the expiration time for password reset link like for only 5/10 minutes not for the whole day.After that time completed when user click that link it should display some messages like link disabled,try again. How can i do this? Is it possible ? urls.py path( 'admin/password_reset/', auth_views.PasswordResetView.as_view(), name='admin_password_reset'), path( 'admin/password_reset/done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done', ), settings.py PASSWORD_RESET_TIMEOUT_DAYS = 1 # how can i change it to some minutes ?? -
How to extend Django AuthenticationForm
I'm writing a web app and I want to add a required checkbox to Django's AuthenticationForm I don't know how to extends (or override ?) the AuthenticationForm. Here's where I call the auth form in my template : <h2>Login</h2> <form method="post"> {% csrf_token %} {{ form.as_p}} <button type="submit" class="btn btn-success">Login</button> </form> <br> <p><strong>-- OR --</strong></p> <a href="{% url 'social:begin' 'github' %}">Login with GitHub</a><br> </body> Thanks by advance ! -
Is there a way to make django administration customize the models schema
I would like to know if it's possible to customize django-admin panel so the admin can add attributes to a specific Model. change the name of attribute. Modifying the schema via the admin panel. -
How can I do a query using Django?
Hello I am looking for the equivalent of SQL queries using Django for instance : SELECT * FROM TABLE WHERE CONDITION SELECT COLUMN_1 FROM TABLE WHERE CONDITION UPDATE TABLE SET COLUMN_1 = 'values' WHERE condition I saw different things on the internet so I would like to be sure that is why I ask your help. Thank you ! -
How to store, retrieve, change user specific data in Django?
I am new to django. I have a new application wherein, after user login, each user should enter details like 'Describe yourself', 'percentage' etc. I can create a model and implement it. But how do I map that data to the specific user in 'User model'. And later, the user must be able to alter the data he has entered. Can someone provide the websites or documentations about these aspects. Thank you in advance. -
gunicorn [/etc/systemd/system/gunicorn.socket:6] Unknown section 'Service'. Ignoring
I'm setting up django on digitalocean, they have a setup rule that works this time though gunicorn won't work. First step is setting up the gunicorn service using this command sudo nano /etc/systemd/system/gunicorn.service and the content [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=sammy Group=www-data WorkingDirectory=/home/sammy/webapp/prestige ExecStart=/home/sammy/webapp/envs/prestige/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/sammy/webapp/prestige/prestige.sock prestige.wsgi:application [Install] WantedBy=multi-user.target note that this directory /home/sammy/webapp/prestige is the main folder directory of django with manage.py so basically if I cd into it I can run python manage.py runserver and it works. this is the folder for the virtualenv /home/sammy/webapp/envs/prestige now when I run the start gunicorn command I get this (prestige) sammy@prestige:~/webapp$ sudo systemctl start gunicorn.socket Failed to start gunicorn.socket: Unit gunicorn.socket is not loaded properly: Invalid argument. See system logs and 'systemctl status gunicorn.socket' for details. if you check the status (prestige) sammy@prestige:~/webapp$ sudo systemctl status gunicorn.socket ● gunicorn.socket - gunicorn daemon Loaded: error (Reason: Invalid argument) Active: inactive (dead) May 17 07:25:18 prestige systemd[1]: [/etc/systemd/system/gunicorn.socket:6] Unknown section 'Service'. Ignoring. May 17 07:25:18 prestige systemd[1]: gunicorn.socket: Unit lacks Listen setting. Refusing. May 17 07:33:32 prestige systemd[1]: [/etc/systemd/system/gunicorn.socket:6] Unknown section 'Service'. Ignoring. May 17 07:33:32 prestige systemd[1]: gunicorn.socket: Unit lacks Listen setting. Refusing. May 17 07:34:09 … -
Is it good to have 2 servers running for caching?(Django & Node.js)
I am trying to implement Redis for caching data using the GeoSpatial queries. Currently I am running a Node.js server with express. What I am confused is! should I use Redis package from Node.js and implement caching in a single server or should I implement Redis on python with Django as server and run 2 servers. On a long term basis which would be the best choice? if there is a better thing I can do here please let me know! Thanks & Regards in advance! -
How to save file in BinayField using Django Form
I am new in Django. please help. I want to save image in BinaryField using form but it's not working. instead of upload in media folder, I want to save file Directly in Database using BinaryField. Model.py: class serviceDb(models.Model): Dev = 1 QA = 2 UAT = 3 Production = 4 environment_TYPES = ( (Dev, 'Dev'), (QA, 'QA'), (UAT, 'UAT'), (Production, 'Production'), ) application = models.CharField(db_column='Application', max_length=255, blank=True, null=True) # Field name made lowercase. startdate = models.DateField(null=True) expiredate = models.DateField(null=True) environment_type = models.PositiveSmallIntegerField(choices=environment_TYPES) CSR=models.BinaryField(editable=True) Form.py: class serviceForm(forms.ModelForm): app_attributes = {'oninvalid': 'this.setCustomValidity("Application field is required")', 'oninput': 'this.setCustomValidity("")'} startdate = forms.DateField(widget = forms.SelectDateWidget(years=range(1995, 2100))) expiredate = forms.DateField(widget = forms.SelectDateWidget(years=range(1995, 2100))) application = forms.CharField(widget=forms.TextInput(attrs=app_attributes)) CSR = forms.FileField(required=False) class Meta: model = serviceDb fields = ('application', 'startdate', 'expiredate', 'environment_type','CSR' ) error_messages = { 'application': { 'required': ("Application field is required"), }, } -
Postgres: Search by annotated/concatenated json values
I have a django model that uses postgres json column. class ClassName: json=JsonField() This is the schema in the json field. { 'lev1': { 'lev2': { first_name: 'Alex', last_name: 'Anderson', street: '242 Bell St,', city:'New York', state:'NY', } } Now I have this data, I have to filter it by with the user's full_name and full address. I am looking for something like ClassName.objects.annotate( full_name=Concat(F('lvl1__lvl2__first_name'), Value(' '), F('lvl1__lvl2__last_name')), full_address=Concat(F('lvl1__lvl2__address'), Value(' '), F('lvl1__lvl2__city'), Value(' '), F('lvl1__lvl2__state'), Value(' '), F('lvl1__lvl2__zipcode')), ).filter(full_name__icontains="Alex Anderson") I have tried all different json functions, not able to get the right combination. -
Django - EmailMessage working in shell but dont working in view with same data
I want to send mail after form valid. So i using EmailMessage class. My code like this. EmailMessage(subject='ddd', body='ff2', from_email='test@gmail.com', to=['test@gmail.com'], reply_to=['test@gmail.com'], headers={}).send() This code work very well in django shell. But not work when i use to in django views. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'test@gmail.com' EMAIL_HOST_PASSWORD = password_create_with_google_app EMAIL_PORT = 587 DEFAULT_FROM_EMAIL = EMAIL_HOST_USER -
convert function in a view to an asynchronous one . django/python
I would like to have your opinion on how to convert following function to asynchronous one. def currency_converter(price, curr1="SEK", curr2="EUR"): c = CurrencyConverter() try: return c.convert(price, curr1, curr2) except ValueError or RateNotFoundError as err: return str(err) This function takes price, 2 currencies codes and convert price to the chosen currency. Problem is when you use this function in cycle, it takes a while to send and receive requests to / from web host for each iteration ( around 2-3 secs for 20 requests) This function is used in the following VIEW in DJANGO: class BlocketView(DetailView): model = BoatModel template_name = 'blocket.html' def get_context_data(self, **kwargs): context = DetailView.get_context_data(self, **kwargs) context["blocket"], context['pricelist'] = (spider(self.kwargs.get("name"))) context["pricelist_euro"] = [currency_converter(price) for price in context['pricelist']] return context Here it gets prices from pricelist and makes new context["pricelist_euro"] list with the converted prices. Also this function might be used as a template tag: @register.filter def currency_converter(price, curr1="SEK", curr2="EUR"): c = CurrencyConverter() try: return c.convert(price, curr1, curr2) except ValueError or RateNotFoundError as err: return str(err) Is it any chance to convert this function to asynchronous one somehow? Thank you -
how to use same dynamic header in all views django
here i have some logo and image and they are dynamic.i want to apply them in all the view but for that i have to pass site_data context to each view and it becames very time consuming.So isn't there any tricks or methods so that i can pass site_data context to all the view at one time models.py class SiteSetting(models.Model): background_image = models.ImageField(upload_to='Background Image',default='NoImageFound.jpg') logo = models.ImageField(upload_to='logo',default='NoImageFound.jpg') views.py def view_student(request): students = Student.objects.all().order_by('-date') year = datetime.datetime.today().year site_data = SiteSetting.objects.all().order_by('-date') return render(request, 'admin/view_students.html', {'admin': students, 'site_data':site_data,'year_list': range(2016, year + 1), 'title': 'All Students'}) def add_student(request): #.... def edit_student(request): def delete_student(request): def view_course(request): def view_teahcer(request): tempplate {% for data in site_data %} {% if forloop.first %} <link rel="icon" href="/media/{{data.logo}}"> {% endif %} {% endfor %} -
How can i write decorations for User and other Models in django?
i have a question about writing decorations in django. i have table Token below, when user click to logged_in with token, i want to redirect to home and is_logged_in field became True. But when User doesn't choose any Token, i want to redirect to list-tokens for people choose token to login that they want. So how can i write decorations when people not yet choose any Token and redirect people to token-lists. Thanks This is my Token model: class Token(models.Model): access_token = models.CharField(max_length=255) user = models.ForeignKey(CustomeUser, related_name='tokens', on_delete=models.CASCADE) is_logged_in = models.BooleanField(default=False) def __str__(self): return self.access_token -
Multiple file upload the easiest way in django
I have to create a form to make a post with fields like Title, description and images. I could successfully create a post with a single image, but when it comes to multiple images, it is not getting saved. Upon research found that i have to use a separate model and form for images. But i cannot see how is it accomplished in the views. So how do i accomplish this the easy way? Models.py class news(models.Model): title = models.CharField(max_length=100) description= models.TextField(max_length=500) class newsimages(models.Model): image = models.ImageField(upload_to='/images/') related = models.ForeignKey(news,on_delete=models.CASCADE,null=True) -
Calculating the sum on two groups without using two querysets?
I am pretty new to Django & Python.. I am grouping transactions by their assigned category and want to sum them by their parent category. Then display a nested list grouped by the parent category, next to it, the sum, then a nested list with the sub-categories listed and next to it the sum. The first solution I had in my head is of course sending two queries to the DB to get the sum once for all the categories of each transactions and then grouping by the parent category: main_qs = Transaction.objects.values('category__parent').annotate(credits=Sum('credit')).annotate(debits=Sum('debit')).filter(category__isnull=False) sub_qs = Transaction.objects.values('category').annotate(credits=Sum('credit')).annotate(debits=Sum('debit')).filter(category__isnull=False) this violates DRY so I though I do it in one query and I found the regroup template tag which i used to regroup the QS based on the parent category. VIEW category_qs = Transaction.objects.values('category__parent','category').annotate(credits=Sum('credit')).annotate(debits=Sum('debit')).filter(category__isnull=False) context = { 'active': 'statistics', 'query' : category_qs, } return render(request, 'stats.html', context) QUERY SELECT categories.parent_id, transactions.category_id, CAST(SUM(transactions.credit) AS NUMERIC) AS credits, CAST(SUM(transactions.debit) AS NUMERIC) AS debits FROM transactions INNER JOIN categories ON (transactions.category_id = categories.id) WHERE transactions.category_id IS NOT NULL GROUP BY categories.parent_id, transactions.category_id ╭───╥───────────┬─────────────┬─────────┬────────╮ │ ║ parent_id │ category_id │ credits │ debits │ ╞═══╬═══════════╪═════════════╪═════════╪════════╡ │ 1 ║ 1 │ 5 │ 0 │ 15 │ │ … -
How to restrict the access to a page through the search bar?
So, I am working on this project where is login page and if a user has forgotten his password he is able to reset through the link that is on the login page, when the user clicks on this link he is being redirected to the page where he has to enter the email, finally he is on the done page. But if a user knows the route to the done page, he can get to this page through the search bar. How to restrict the access to a page through the search bar? -
get __str__() value from Django ForeignKey
I'm trying to get the __str__() from a Foreign key field in django. I tried: field_name = model._meta.get_field(field) field_name.value_from_object(value).__str__() But I got the pk. -
Django - delete recently created objects across database
Is there a way to delete like, all the objects that have been created in the last 10 mins across all the models? Or atleast across 1 model? Unfortunately, I am not storing any created field in those models. Database - Postgresql -
Custom pages can only be queried on local host - PagesAPIEndpoint
Can somebody tell me why my api_router.register_endpoint('pages', PagesAPIEndpoint) can only be queried on localhost? api_router.register_endpoint('images', ImagesAPIEndpoint) works either way. I am trying to figure out the difference between 65 and 1007 because the last number seems a bit arbitrary. Successful attempt on api/v2/images is 446 curl http://192.168.10.220:8000/api/cms/v2/pages/ { "meta": { "total_count": 0 }, "items": [] } web_1 | [17/May/2019 05:52:35] "GET /api/cms/v2/pages/ HTTP/1.1" 200 65 curl http://localhost:8000/api/cms/v2/pages/ { "meta": { "total_count": 2 }, "items": [ { "id": 4, "meta": { "type": "cms.ArticlePageIndex", "detail_url": "http://localhost/api/cms/v2/pages/4/", "html_url": "http://localhost/api/cms/", "slug": "article", "first_published_at": "2019-05-05T04:43:25.433000Z" }, "title": "article" }, { "id": 5, "meta": { "type": "cms.ArticlePage", "detail_url": "http://localhost/api/cms/v2/pages/5/", "html_url": "http://localhost/api/cms/txa709-treats-mrsa-infection-and-restores-efficacy-cefdinir/", "slug": "txa709-treats-mrsa-infection-and-restores-efficacy-cefdinir", "first_published_at": "2019-05-05T05:05:02.483000Z" }, "title": "TXA709 treats MRSA infection and restores efficacy of cefdinir" } ] } web_1 | [17/May/2019 05:52:35] "GET /api/cms/v2/pages/ HTTP/1.1" 200 1007 I even added the custom url to ALLOWED_HOSTS. I should be running a dev build -
-DJANGO- My following function doesn't seem to work?
I'm making a twitter clone, but I'm stuck right now on the following and followed problem, I wrote the code that can enable users to follow and unfollow a user but it's not working. Even though everything seems to be right. Here is the models.py class ProfileManager(models.Manager): def all(self): qs = self.get_queryset().all() if self.instance: qs = qs.exclude(user = self.instance) else: pass return qs def toggle_follow(self, user, to_toggle_user): user_profile, created = Profile.objects.get_or_create(user=user) # (user_obj, true) if to_toggle_user in user_profile.following.all(): user_profile.following.remove(to_toggle_user) added = False else: user_profile.following.add(to_toggle_user) added = True return added def is_following(self, user, followed_by_user): user_profile, created = Profile.objects.get_or_create(user=user) if created: return False if followed_by_user in user_profile.following.all(): return True return False class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,related_name = "profile") following = models.ManyToManyField(settings.AUTH_USER_MODEL,blank = True,related_name = "followed_by") objects = ProfileManager() Here is the views.py for UserFollow class UserFollow(View): def get(self,request,username,*args,**kwargs): toggle_user = get_object_or_404(User, username__iexact=username) if request.user.is_authenticated(): is_following = Profile.objects.toggle_follow(request.user, toggle_user) return redirect("accounts:detail",username=username) When the UserFollow view executes it should do the thing and then redirect but it doesn't redirect which doesn;t complete the whole view . I think that maybe the case why it's not working. Here is the template code for the follow and unfollow <a href='{% url 'accounts:follow' %}'class="btn btn-info"> {% if … -
Windows Apache 2.4 can't upload or create files in /media folder using Django
In this project I have to use Windows 10 and Apache 2.4 to serve a web application. Everything works fine apart from the fact that I cannot upload images to the /media folder or let Django/Apache/mod_wsgi create files and store them in /media folder. In apache conf file I have granted all necessary permissions: <Directory "c:/Users/holistic/workspace/vitadmin/vitadmin/media"> Require all granted </Directory> Media files can be served but cannot be uploaded by user. Additionally, when Apache tries to create and store a file in /media/csv folder (for user to download later) I get this error You don't have permission to access /media/csv/ on this server. However, all permissions have been granted for this folder, too. <Directory "c:/Users/holistic/workspace/vitadmin/vitadmin/media/csv"> Require all granted </Directory> In the first case (when I try to upload the file) I get this error: Django Version: 1.8.5 Exception Type: RuntimeError Exception Value: generator raised StopIteration Exception Location: c:\users\holistic\envs\vitadmin\lib\site-packages\django\http\multipartparser.py in read, line 337 Python Executable: C:\Apache24\bin\httpd.exe Python Version: 3.7.3 (full traceback here: http://dpaste.com/16E4M41) I have a feeling that this might be more of a Windows 10 issue (exact same project works fine in Linux/Nginx/Gunicorn, but due to customer needs I have to migrate it to Windows 10 / Apache). For that … -
How do i assign foreign key value to my post
# This my part of CreateView def post(self, request, *args, **kwargs): form = BussinessDetailForm(request.POST,request.FILES or None) form2 = MultipleImageForm(request.POST or None, request.FILES or None) files = request.FILES.getlist('images') if all([form.is_valid(),form2.is_valid()]): forms = form.save(commit=False) geolocator = Nominatim() location = geolocator.geocode(self.request.POST.get("pin_code",False)) forms.latitude = location.latitude forms.longitude = location.longitude forms.created_by = self.request.user forms.themes = self # forms.object_id = int(self.request.POST.get("id",False)) forms.save() # part of models.py class BussinessDetail(models.Model): # content_type = models.ForeignKey(ContentType,on_delete = models.CASCADE) # object_id = models.PositiveIntegerField() # content_object = GenericForeignKey('content_type','object_id') themes = models.ForeignKey(Themes,on_delete=models.CASCADE,primary_key=False) # object_id = models.PositiveIntegerField() created_by =models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,primary_key=False) listin_catagory =models.CharField(max_length=200,choices=listin_Catagory,blank=True) bussiness_name =models.CharField(max_length=200,blank=True) #themes table class Themes(models.Model): theme_created_by =models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,primary_key=False) default_theme = models.BooleanField(blank=True,default=False) technology_theme = models.BooleanField(blank=True,default=False) -
Django application does not fetch latest entries from remote database
I have a simple Django application which fetches remote database entries and displays it in table form. To host the application, I have simply forked the command python manage.py runserver. If I restart this command manually, the latest entries of database are fetched else those entries are the old ones. Could someone let me know how could I fix that? class Student: def __init__(self): self.connection = connections['db'] def get_all_entries(self): with self.connection.cursor() as cursor: cursor.execute(query['students']) database_entries = dictfetchall(cursor) cursor.close() self.connection.close() return database_entries Note: I am using Django 2.2.1