Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The safe is not working after creating hashtag system for my Django project
I made a hashtag system for my Django project but after making it the safe isn't working and if a user wants to use special characters it shows weird in output. Example I want to write: " Hello, I'm Ramin " it will show " Hello, I & #x27;m Ramin " Can anyone help me? -
Django query how to write: 'WHERE field LIKE' in Cassandra
What is the equivalent of this CQLSH statement in Django? SELECT * FROM table_name WHERE string LIKE pattern; How do I implement this in django? I tried result = table.objects.filter(string__contains='pattern') but it is giving the following error [Invalid query] message="Cannot use CONTAINS on non-collection column string" I have already made a custom index for the search field and raw LIKE query is working in cqlsh. But I need something for Django to filter on basis of keyword. Thanks in advance -
How to install Figures Plugin for openedx koa release
Hi I am using openedx koa.2 release and want to install appsembler figures reporting plugin.Since figures doesn’t support koa.2 is there anyway to install figures for koa2 release.enter link description here -
Python Django models id increment by 2
is it possible to increase the auto increment in django models id: class Role(models.Model): id = models.AutoField(primary_key=True) # I need to get Integer field, increment=2 uuid = models.CharField(max_length=36, unique=True) Should I overwrite the .save() method? -
problem with deploying django project on heroku
i can't deploy my website because of favicon problem (i don't have favicon on my static) 2021-03-10T05:27:41.838422+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=sausagepolls.herokuapp.com request_id=81a5685f-9561-4523-bdd0-b276d66f99c3 fwd="156.214.1.142" dyno= connect= service= status=503 bytes= protocol=https 2021-03-10T05:27:42.124704+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=sausagepolls.herokuapp.com request_id=018aa90c-998f-48d4-9cba-1c1473edde29 fwd="156.214.1.142" dyno= connect= service= status=503 bytes= protocol=https -
Convert two lists into a dictionary of X and Y Format
I have two lists containing around 300 decimal numbers. That I need to convert into a dictionary format like below in order to plot a scatter graph using the values within the two lists as X and Y coordinates with Chart.JS. This is the format that Chart.JS requires the data to be in. data: [{ x: -10, y: 0 }, { x: 0, y: 10 }, { x: 10, y: 5 }] I've been trying to do this in a number of different ways but each time I get it wrong. Does anyone know a good way to accomplish this? -
Django Extending User Model - Inherit Profile Form from Model
I am following a tutorial to do this in Django 3.1.7. The problem I'm having here is I'm being forced to repeat my Profile Model in my Profile Form definition. I want to use forms.ModelForm in my forms.py to inherit my Profile Model and auto-generate the forms. It seems redundant to have to spell everything out again in forms.py when it is already defined in my Models. But I'm not sure how to do that with this architecture. I've tried this approach: https://stackoverflow.com/a/2213802/4144483 But the problem with this is that UserForm is incomplete - 'password1' and 'password2' don't exist for model User. This is not a good solution for user registration. I seem to be bound to using UserCreationForm somehow. #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 = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() #forms.py rom django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class SignUpForm(UserCreationForm): birth_date = forms.DateField(help_text='Required. Format: YYYY-MM-DD') class Meta: model = User fields = ('username', 'birth_date', 'password1', 'password2', ) #views.py from … -
csrf token not working when user logged in react js axios django
when i log out and try to post it works but when i log in and try to post it does not work and gives me 403 error , react file class Axios extends React.Component{ constructor(){ super() this.state = { persons: [] } } post(){ axios.post('http://127.0.0.1:8000/api/create', { title: 'titan', body: 'this is working', headers:{ withCredentials: true, 'X-CSRFToken':CSRF_TOKEN, 'Accept': 'application/json', 'Content-Type': 'application/json', }, }) .then(function (response) { console.log(response); }) } get(){ axios.get('http://127.0.0.1:8000/api').then(Response=>{ console.log(Response.data) }) } componentDidMount(){ this.post(); this.get(); } render(){ return( <div> <h1>fetch</h1> </div> ) } } export default Axios; views.py class create(CreateAPIView): queryset = Post.objects.all() serializer_class = postSerializers also added this in setting.py CSRF_COOKIE_NAME = "X-CSRFToken" when logged in when logged out if there anyone who is clever enough pls help me on this.. trying to find the solution for days... -
Dryest way to use a ManyToManyField to store values in model
I've created a real estate back end website with Django and I'm creating a way to track how agents are performing in various cities on Zillow in terms of reviews. While I could create a model that looks like this: class Agent(models.Model): url_los_angeles = models.URLField(default="https://zillow.com/los_angeles") rank_los_angeles = models.IntegerField(default=0) url_san_diego = models.URLField(default="https://zillow.com/san_diego") rank_san_diego = models.IntegerField(default=0) This doesn't seem like a very smart way to do this. Using a ManyToManyField field seems like the right approach, but I don't quite see how this would work. For example, how would an agent's individual ranking be store in the many to many field? Any insight would be greatly appreciated. -
Applying local timezone in Django templates
I use Django 3.1.7 and postgreSQL for the database. So here is the problem, after saving a date in my database I try to display it in a template with the timezone of the visitor and it's still displaying me the date UTC. I have these values in my settings.py: LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True my model: class Log(models.Model): user = models.ForeignKey(to=User, on_delete=models.PROTECT) log = models.CharField(max_length=255) type = models.CharField(max_length=50) date = models.DateTimeField(auto_now_add=True) company = models.ForeignKey(to=Company, on_delete=models.PROTECT) my context processor getting me the objects: def logs_processor(request): if request.user.has_perm('loging.can_see_logs'): try: logs = Log.objects.filter(company=request.user.company).order_by('-date')[:50] except TypeError: logs = None return {'side_logs': logs} else: return {'side_logs': []} And my template: {% load tz %} {% for log in side_logs %} {{ log.date|localtime }} {% endfor %} I tried without the |localtime but no luck. When I specify by hand the TZ like log.date|timezone:"Europe/Paris" That works well. As well I precise that I have pytz installed. Here what my dates look like in the database (it seams they are not naive and placed on UTC as planed): 2021-03-10 04:10:11.849048 +00:00 Any idea? -
Don't acctually now how to use ForeginKey in my issue. No idea where the problem is, looked out for HOW TO "ForefinKey use"
In my case I want, to use ForeginKey field. I want to build app something like "Items added by user and I want get ready and clear order with unique ID and items passed by user". Add items Make order with status etc. I stucked almost at the begining... models.py class Item(models.Model): width = models.CharField(max_length=5) length = models.CharField(max_length=5) description = models.CharField(max_length=255) def __str__(self): return "%sx%s" % (self.width, self.length) class Order(models.Model): STATUS = ( (0, 'pending'), (1, 'during'), (2, 'done')) costumer = models.ForeignKey(settings.AUTH_USER_MODEL, blank=False, on_delete=models.CASCADE) item = models.ForeignKey(Item, blank=False, on_delete=models.CASCADE) startDate = models.DateTimeField(auto_now_add=True) status = models.IntegerField(default=0, choices=STATUS) slug = models.SlugField(blank=False, unique=True, default=create_randomSlug()) def __str__(self): return "Zamówienie ID#%s z dnia %s" % (self.slug, self.startDate) def get_absolute_url(self): return 'order/%s' % self.slug from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import Order, Item, Costumer from django.contrib.auth.mixins import LoginRequiredMixin from django.conf import settings views.py class Home(LoginRequiredMixin, ListView): model = Order paginate_by = 100 template_name = "home.html" def OrderDetail(request, slug): order = Order.objects.get(slug=slug) context = {'order': order, } return render(request, 'order_detail.html', context) order_detail.html {% extends 'base.html' %} {% block content %} <!-- Top header --> <header class="w3-container w3-xlarge"> <p class="w3-center">Zamówienie #{{ order.slug }}</p> </header> <div class="table-wrapper"> <table class="fl-table"> <thead> <tr> <th>Lp.</th> <th>Długość</th> <th>Szerokość</th> … -
how to use country name as default instead of code in django-countries package
I am using an a django package called django-countries which gives me access to some countries attributes in the world such as country name, country code, country flag and some other more. It seems the default appears to be the country code, i will like to know how to be able to use the country name instead of the default which is the country code. For example in my views, i have a code like this def analyse_market(request): qs = Product.objects.values('country').annotate( number=Count('pk') ).order_by('country') result = { q['country']: q['number'] for q in qs } print(result) context = {"result":result} return render(request, 'core/analyse-market.html', context) This return a result like this: {'AD': 3, 'AR': 5, 'BH': 1, 'FR': 1, 'JP': 1, 'NG': 1, 'NL': 1} In the documentation, they have different methods used such as country.name, country.code, country.flag, I have tried the country.name because it relates to what I need, but i get KeyError when using the country.name in my views. -
User Form not showing django class based views
I am working on Hospital Management System and there are 5-6 different types of users like Patient, Doctor, Nurse, Accountant, Receptionist, etc. I've extended the User model using AbstractUser which has common fields for all users like DoB, address, etc. models.py class User(AbstractUser): # user_type = models.CharField(choices=USER_TYPES, default='patient', max_length=20) date_of_birth = models.DateField(blank=True, null=True, validators=[validate_future_date]) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+9199999999'. Up to 15 digits allowed.") mobile_num = models.CharField(max_length=15, validators=[phone_regex]) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) date_joining = models.DateTimeField(auto_now_add=True) photo = models.ImageField(default="default.png", upload_to="patients/%Y/%m/%d", blank=True) # other fields def __str__(self): return f"{self.first_name} {self.last_name}({self.username})" class Staff(models.Model): aadhar_number = models.BigIntegerField(verbose_name='Aadhar Number') empCategory = models.CharField(max_length=20, blank=True, verbose_name='Employee Category') class Meta: abstract = True class Patient(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) date_of_discharge = models.DateTimeField(auto_now=True) allergies = models.TextField(blank=True, null=True) def __str__(self): return f"{self.user.first_name} {self.user.last_name}({self.user.username})" class Doctor(models.Model): DEPARTMENTS = [('Cardiologist', 'Cardiologist'), ('Dermatologists', 'Dermatologists'), ('Emergency Medicine Specialists', 'Emergency Medicine Specialists'), ('Allergists/Immunologists', 'Allergists/Immunologists'), ('Anesthesiologists', 'Anesthesiologists'), ('Colon and Rectal Surgeons', 'Colon and Rectal Surgeons') ] user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) languages = models.CharField(max_length=20) speciality = models.CharField(max_length=20) department = models.CharField(max_length=50, choices=DEPARTMENTS) # patients = models.ManyToManyField(Patient, related_name='doctors') def __str__(self): return f"{self.user.first_name} {self.user.last_name}({self.user.username})" class Receptionist(Staff): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) # patient = models.ManyToManyField(Patient, related_name='receptionists', blank=True) def __str__(self): return f"{self.user.first_name}" class … -
Django Push Notification
I wrote django app for my backend app (Android client), but i haven't idea for push notif or push data to specific client. There are exist tutorial with django-websocket. I read documentation and then conclude that websocket use group for push data. So, user subscribe to group then server push data to all user in group. This did't resolve my problem. I think open new socket based on (TCP) in-same machine (ex. port 5008) for listening client. After client request i will save data connection like address with UID, so i will send data with low socket to client while client already register. Does it work? And Secure? Please remind if there is an wrong theory. Thanks!! -
What type of lookup can i use for a foreign key field in django
I have a search form in my application. I am performing some request with it within the database of my application. The category field is a foreign key relationship in my application. When trying to make a search, i got this error because the category is a foeirgn key and perhaps i used the wrong lookup expression for this. What is the right way i can go about this please? Thanks Error log Exception Type: FieldError at /searchproduct/ Exception Value: Related Field got invalid lookup: icontains models.py class Category(models.Model): name = models.CharField(max_length=256) class Product(models.Model): name = models.CharField(max_length=36) price = models.PositiveIntegerField() description = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE) views.py def search(request): if request.method == 'GET': product_name = request.GET.get('search') products = Product.objects.filter(category__icontains=product_name) or Product.objects.filter(name__icontains=product_name) context = {"products": products} return render(request, "core/search.html", context) else: result = "Sorry there is no product with that name" return render(request, "core/search.html", context) -
Invalid resource lookup data provided (mismatched type) in obj_get_list
I'm having an issue with django-tastypie with tastypie_mongoengine. So I've designed a model that lists contacts from a collection at my MongoDB, all methods are working well except obj_get_list that when called from endpoint myhost/api/v1/contacts raise this error { "error": "Invalid resource lookup data provided (mismatched type)." } So this is how I have structured my model: class ContactResource(resources.MongoEngineResource): class Meta: queryset = Contact.objects.all() allowed_methods = ('get', 'post') resource_name = 'contacts/contact' authorization = CustomerObjectsOnlyDjangoAuthorization() authentication = ApiKeyAuthentication() always_return_data=True paginator_class = Paginator filtering = { "customer_id": [ "exact", ], "campaigns": ["match", ], "id": ["exact", ], "email": ["exact", ], } limit=100 def dehydrate(self, bundle): customs = bundle.data['customs'] if 'customs' in bundle.data: del bundle.data['customs'] excludes = ['customer_id', 'is_spamtrap'] for exclude in excludes: if exclude in bundle.data: del bundle.data[exclude] for c in customs: if c.get('k'): bundle.data[c['k']] = c['v'] return bundle def obj_get_list(self, bundle, **kwargs): if bundle.request.GET.get('campaigns__match'): campaigns = int(bundle.request.GET.get('campaigns__match')) self._meta.queryset = self._meta.queryset.filter(__raw__={'campaigns':{'$elemMatch':{'id': campaigns}}}) if not bundle.request.user.is_staff: kwargs['customer_id'] = bundle.request.user.get_profile().customer.id self._meta.queryset = self._meta.queryset.filter(customer_id=kwargs['customer_id']) return super(ContactResource, self).obj_get_list(bundle, **kwargs) If I call the end point myhost/api/v1/contacts/contact/contac-id I can make it and get data for a specific contact, but to list all the error mentioned above appears Any Help? -
Django: connect social media local user but disallow login using social media credentials
Problem: My Django webapp allows users to login using email/password. Now I need to connect their one or more social accounts to the existing account but only for the purpose of accessing their social media content. They will not be able to login in to my webapp using their social credentials. They still have to use the existing email/password to login in to my webapp. Work so far: I have looked at django-allauth and python-social-auth but not sure if I can be selective about not allowing login but still connect the social accounts. Question: So is it possible to achieve this using django-allauth or python-social-auth ? Is there a simpler method ? Thanks ! -
My Django Project now won't run Python3 manage.py runserver
So I seen this issue here on stack, but for a few slightly different reasons and I can't manage to figure it out for myself. I'm getting this error in my terminal: Traceback (most recent call last): File "manage.py", line 10, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 12, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? and YES i do have django installed. I'm currently working on the Harvard CS50W project and it was working perfectly fine until i updated my python through HomeBrew. Now my project can't locate django to run the server. I seen stuff online about the virtualenv but I didn't need to set one up prior to starting this project. So I'm not sure what to do in order to get my project back up and running. If someone could please help that would be great! Thanks! Also should mention I'm using the M1 Mac. … -
python remove duplicate element from list
In python i am getting a list in a variable like : [ {'store_id': '321', 'first_name': 'A', 'name': 'A'}, {'second_id': '322', 'first_name': 'B', 'name': 'B', }, {'second_id': '323', 'second_name': 'c', 'name': 'c', }, {'second_id': '324', 'second_name': 'A', 'name': 'A', }, ] what i actually want is i want a list without duplicating the name . if it occur once then i want to remove t and create a new list with distinct data.i am stuck here i want all data in new list. how can i remove the duplicate data from the list . in my case i want a ne list like : Either {'second_id': '322', 'first_name': 'B', 'name': 'B', }, {'second_id': '323', 'second_name': 'c', 'name': 'c', }, {'second_id': '324', 'second_name': 'A', 'name': 'A', }, ] Or [ {'store_id': '321', 'first_name': 'A', 'name': 'A'}, {'second_id': '322', 'first_name': 'B', 'name': 'B', }, {'second_id': '323', 'second_name': 'c', 'name': 'c', }, ] -
Can't pass null fields into django floatfield?
(approach inspired by this thread) I have some json data that I want to import into django models using the example data: [{"orderID": "2b062ac4542172b12f47e2b26d1629ae", "status": "No Car", "specialRequest": "", "endedTime": "2018-12-01T00:02:34HKT", "tunnel": "", "pickedTime": null, "toLocation": {"lat": "22.307488971554207", "lng": "114.2600533354737", "displayName": "\u5c07\u8ecd\u6fb3", "locality": "\u5c07\u8ecd\u6fb3"}, "memberID": "c8dfb02f6d81394582f3ceac57749616", "fromLocation": {"lat": "22.3172022", "lng": "114.16995739999993", "displayName": "\u5f4c\u6566\u9053\u502b\u6566\u5927\u9152\u6a13", "locality": "\u65fa\u89d2"}, "specialRequestText": "85\u6298", "cancelReason": null, "createdTime": "2018-12-01T00:00:00HKT", "paymentMethod": "Cash", "extraTips": 0} This is my model for Member thus far: class Member(models.Model): member_id = models.CharField(max_length=32, primary_key=True) member_loc_lat = models.FloatField(default= None, null=True, blank=True) member_loc_long = models.FloatField(default= None, null=True, blank=True) # blank to be able to pass in null values, null to tell the DB to accept null values member_locality = models.TextField() member_display_name = models.TextField() member_created_time = models.DateTimeField(auto_now=False, auto_now_add=False) def __str__(self): return self.member_id And this is the script that loads the member-related fields (from the json file) into my Member model: import json import argparse import django from django.conf import settings import sys import os import pymysql pymysql.install_as_MySQLdb() from mysite.models import Member, Driver, Order def main(): parser = argparse.ArgumentParser() parser.add_argument("-i", "--input", type=str, required=True, help="path to original data file (.data)") args = parser.parse_args() data_members = {} # type list with open(args.input) as f: data_members = json.load(f) for member in range(len(data_members)): … -
Save Django .sqlite3 file in two separate paths
I am trying to deploy an application using SQLite3 as the database and I need to have the same database file stored in two separate paths for production purposes. Is this possible and if so, how? -
Captcha doesn't work, why is this happening?
My captcha appears at the bottom on the right and it's only the logo, there is no challenge and not input bar. Why is this happening? This is the html: <!DOCTYPE HTML> <html> <head> <title>Constancia</title> <script src="https://www.google.com/recaptcha/api.js?render=MYKEY"></script> <script> function onSubmit(token) { document.getElementById("demo-form").submit(); } </script> </head> <body> <div class="header"> </div> <div class="wrap"> <header></header> <form action='/constancia-inscripcion' method="POST"> {% csrf_token %} <label for="cuit">CUIT:</label> <input type="number" name="CUIT"> <label for="email">Email:</label> <input type="text" name="Email"> <input type="hidden" name="g-recaptcha-response" id='recaptcha' > <button type="submit" name="Solicitar constancia"></button> </form> </div> This is the captcha in the backend: c_data = { 'response': request.POST.get('g-recaptcha-response'), 'secret': "6LdEnNsZAAAAANeDqX4oOOaPnidRtoG9yMApCl_t" } resp = requests.post('https://www.google.com/recaptcha/api/siteverify', data=c_data) captcha_response = resp.json() if not captcha_response.get('success') or captcha_response.get('score') < 0.6: print("captcha incorrecto") else: print("captcha correcto") -
Increasing an integer (model variables or view.py dictionary values) by using buttons in Django
Me and my friends are trying to design a translation game website using Django framework. I created a quizloop but I want to add a points system now. I want the point to increase by 10 when the correct answer button is clicked by the player. This is my first time using Django and I couldn't find much explanatory sources for beginners on the Internet. If you are going to suggest using AJAX, JSON or jQuery, I would appreciate explaining your code a bit more in detail. This is my view.py: from django.http import HttpResponse from django.shortcuts import render import random from .models import Test # Create your views here. def question_view(request, *args, **kwargs): randomint = random.randint(1,4) test = Test(questionCounter=1, points=0) question_context = { "Merhaba": "Hello", "Günaydın": "Good Morning", "İyi Akşamlar": "Good Evening", "Bir": "One", "İki": "Two", "Üç": "Three", "Dört": "Four", } dictionary = {"question": random.choice(list(question_context.keys())), "answer1": random.choice(list(question_context.values())), "answer2": random.choice(list(question_context.values())), "answer3": random.choice(list(question_context.values())), "answer4": random.choice(list(question_context.values())), "randomint":randomint, "test": test } if randomint == 1: dictionary["answer1"] = question_context[dictionary["question"]] elif randomint == 2: dictionary["answer2"] = question_context[dictionary["question"]] elif randomint == 3: dictionary["answer3"] = question_context[dictionary["question"]] elif randomint == 4: dictionary["answer4"] = question_context[dictionary["question"]] while dictionary["answer1"] == dictionary["answer2"] or dictionary["answer1"] == dictionary["answer3"] or dictionary["answer1"] == dictionary["answer4"] or dictionary["answer2"] … -
Django Rest Framework Restricting Views
I am building a website that will host multiple apps. Some apps can only be accessed by certain groups from a LDAP backend. To achieve this on a pure Django stack, I used user_has_perm @user_passes_test() so that certain views can only be accessed by users who has permission to add items (I give the permission to add items to certain groups, they are automatically placed into a group from the LDAP) However, I am now migrating to a React + Django stack. How can I achieve a similar effect, where you can only access some apps if you are in the correct LDAP group. Note - I have a single react app frontend that that uses routers to get to different component(apps) -
How can I show the details of a post along with its comments using Django framework?
new to the django framework and a little rusty with coding. I am currently trying to build a tech blog from the ground up and have been using Django Central tutorials as a guide. Currently I am stuck on this tutorial- https://djangocentral.com/creating-comments-system-with-django/#comment-2272, particularly getting my views to show both the details of the post and the comments form. In the tutorial the author switches from a class based view to a function that uses get_object_or_404() in order to retrieve the post. I was able to switch over to this function without any error messages, yet the post detail returns blank. Returning to a class based view solves this issue, but I would like to go with the function provided in the tutorial. Here is the code: views.py def post_detail(request, slug): template_name = 'post_detail.html' post = get_object_or_404(Post, slug=slug) comments = post.comments.filter(active=True) new_comment = None # Comment posted if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): # Create Comment object but don't save to database yet new_comment = comment_form.save(commit=False) # Assign the current post to the comment new_comment.post = post # Save the comment to the database new_comment.save() else: comment_form = CommentForm() return render(request, template_name, {'post': post, 'comments': comments, 'new_comment': new_comment, …