Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I use Django's update_or_create function for a model with multiple fields?
I have a model with many fields. In order to update my model, I make a query for my DB and using the dictfetchall() from Django I get a list of dicts containing the results from the query (each key in each dict is the column name for 1 object). class Enterprise(models.Model): --- primary key here --- ... --- many other fields here --- I want to use the Django's function update_or_create() for updating the existing rows with new information or creating new rows if the object already not exists (based on its pk). But I don't know how to implement this, due to the large number of items. Furthermore, the dict keys are not equal to the name of the field in my model. How can I do this? Than you! -
How do you optimize a django query involving fetching all the rows given that the condition lies in the many to many relationship?
I have a Django model that has 3 foreign keys. This is being used as the through model for another many to many relationship. What I'm trying to do is I'm trying to pass in a list of items and trying to see if I can get a matching Event with the same entities. The problem is, the way I'm doing it feels super dodgy and slow since it's pulling all the possible candidates into memory and THEN checking one by one to see if any of them are the appropriate match. I'm trying to see if there's a better way to optimize this. class Event(models.Model): event_type = models.ForeignKey(EventType, on_delete=models.CASCADE) entities = models.ManyToManyField(Entity, through='EntityToEventMap') class EntityToEventMap(models.Model): entity = models.ForeignKey(Entity, on_delete=models.CASCADE) event = models.ForeignKey(Event, on_delete=models.CASCADE) relationship = models.ForeignKey(Relationship, on_delete=models.CASCADE) # this is the chunk of code that does the searching def some_search(self, entity_relationship_list, *args, **kwargs): for entity, relationship in entity_relationship_list: if queries_component: queries_component |= models.Q(entity=entity, relationship=relationship) else: queries_component = models.Q(entity=entity, relationship=relationship) if queries_component: event_ids = EntityToEventMap.objects.filter(queries_component).filter( event__event_type=kwargs['event_type'], event__event_datetime=kwargs['event_datetime']).order_by( 'event').values_list('event', flat=True).distinct() for event_id in event_ids: if len(entity_relationship_list) == EntityToEventMap.objects.filter(queries_component).filter( event__id=event_id).distinct().count(): print(f'Found a potential candidate event id: {event_id}') -
django DoesNotExist - matching query does not exist
I need little help to solve an issue. When I open the URL I'm getting an error 'Exception Value: UserProfile matching query does not exist.'. I'm not sure how can I fix this. Any help is appreciated. views.py @login_required def edit_profile(request): current_user = UserProfile.objects.get(user=request.user) form = EditProfile(instance=current_user) if request.method == 'POST': form = EditProfile(request.POST, request.FILES, instance=current_user) if form.is_valid(): form.save(commit=True) form = EditProfile(instance=current_user) return render(request, 'login/profile.html', context = {'title' : 'Edit Profile', 'form' : form}) models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user_profile') profile_picture = models.ImageField(upload_to='profile_pictures', blank = True) dob = models.DateField(blank=True, null = True) website = models.URLField(blank = True) facebook = models.URLField(blank = True) forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import UserProfile class CreateNewUser(UserCreationForm): email = forms.EmailField(required=True, label = '', widget = forms.TextInput(attrs={'placeholder':'Your Email'})) username = forms.CharField(required=True, label = '', widget = forms.TextInput(attrs={'placeholder':'Your Username'})) password1 = forms.CharField( required=True, label = '', widget = forms.PasswordInput(attrs={'placeholder':'Password'}) ) password2 = forms.CharField( required=True, label = '', widget = forms.PasswordInput(attrs={'placeholder':'Confirm Password'}) ) class Meta: model = User fields = ('email','username', 'password1', 'password2') class EditProfile(forms.ModelForm): dob = forms.DateField(widget=forms.TextInput(attrs={'type':'date',})) class Meta: model = UserProfile exclude = ('user',) -
What does serialize=False mean in the migration for a Django model?
Here is some code from a Django 3.1 migration: migrations.AlterField( model_name='foo', name='blarg', field=models.BigIntegerField(default=theapp.util.make_id, primary_key=True, serialize=False), ), What does the serialize=False mean in this context? I read some code and docs, and it wasn't obvious. -
Django URL matching a trailing slash
If I add to my urls.py urlpatterns += [url(r'^(\S+)$', views.myview, name='myview') ] I expect it to match "mysite.com/anything/" but it does not. Navigating to that URL in my browser adds "Not Found: /anything/" to my "error.log". It only appears to match URLs that do NOT end with "/". Why? I tried explicitly adding the slash at the end urlpatterns += [url(r'^(\S+)/$', views.myview, name='myview') ] but still no match to "mysite.com/anything/" -
Accidentally Deleted (overwrote) Local Files in Git Repo
I executed the command git checkout -f branchName on my terminal. That made all of the changes to files I have been working on for four days go away, as I have overwritten them. The worst part is that I didn't save my files anywhere, nor did I commit previous changes. Is there any way out from this situation? Can I restore my lost files and changes? -
Auto many-to-many relations
I need help working with many-to-many relationships. I have an example code with some models to explain it better: class Company(models.Model): company_name = models.CharField(max_length=30, null = False) ------------------------------------------------------------------- class Post(models.Model): name = models.CharField(max_length=20, null = False) company_id = models.ForeignKey(Company, on_delete=models.CASCADE) ------------------------------------------------------------------- class User(AbstractUser): name = models.CharField(max_length=255, null = False) company_id = models.ForeignKey(Company, on_delete=models.CASCADE) posts = models.ManyToManyField(Post, through='PostPerUser') ------------------------------------------------------------------- class PostPerUser(models.Model): company_id = models.ForeignKey(Company, on_delete=models.CASCADE) user_id = models.ForeignKey(User, on_delete=models.CASCADE) post_id = models.ForeignKey(Post, on_delete=models.CASCADE) view_post = models.BooleanField(default=False) I need that whenever a 'User' is created in the 'Company', it automatically creates a connection with all the 'Posts' of that 'Company'. And when a new 'Post' is created that automatically creates a connection with all the 'Users' of that 'Company'. The "view_post" field will decide whether that 'User' will see the 'Post' or not, so that a 'User' with a given permission can decide that. Does anyone know how i can do this? I never had to do anything like that before and I would appreciate the help, thanks! -
jQuery click function with Ajax post duplicated
I'm using jQuery, Ajax with Django to do post: $("#comment_content").click(function(){ $(".comment_btn").click(function(){ var pid=""; var content =$("#comment_content").val(); $.ajax({ url:"/news/comment/", type:"post", data:{ "news_id":"{{news.pk}}", "content":content, pid:pid, }, beforeSend: function (xhr, settings) { xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}"); }, success:function(data){ $("#comment_content").val(""); var create_time = data.create_time; var username = data.username; var content = data.content; var s = ` <p>${create_time}</p> <p>${username}</p> <p>${content}</p> `; $(".comment_list").append(s); } }) }) }) The first post is ok, but if I don't refresh the page, the second the post will be duplicated. this is post 1 this is post 2 this is post 2 Any friend can help? -
Where does Django-oauth-toolkit store the client_id and client_secret?
When an application is created and issued a client_id and client_secret using django-oauth-tookit where does it store the client_id and client_secret? How can I manually retrieve/create them? -
Django OAuth toolkit: Automatically generate a client_id and client_secret for new user?
I am using OAuth client credentials to offer my customers access to our API so they can integrate with their systems. To register an application and generate a client_id and client_secret the Django-oauth-toolkit documentation says the form o/applications/register/ must be completed (documentation here). Is it possible to automatically issue a client_id and client_secret to my user when they sign up instead of directing them to this form ? -
Default password for all users in Django
hi I Create users without using the file password, by the problem the form does not validate because the password is required. So How to create a default password for all user? class ProfileUserManager( BaseUserManager) def create_user(self, username, password,**extra_fields): user = self.model(username=username, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, username, password,**extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(username,password,**extra_fields) class ProfileUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) username = models.CharField(max_length=255,unique=True) first_name=models.CharField(max_length=255) last_name= models.CharField(max_length=255) -
Use custom join query with Django ManyToMany relationship
I have a User model which connects to a Role model via a ManyToMany, and then the Role model connects to two models, SitePermission or ForumPermission. Problem is, I can't figure out how to setup that connection. Here are my models, with (I believe) irrelevant fields removed. Role: class Role(): class RoleTypes(models.TextChoices): SITE = "s", "Site" FORUM = "f", "Forum" role_type = models.CharField(max_length=1, choices=RoleTypes.choices, null=True) permissions = models.ManyToManyField( "permissions.Permission", related_name="roles", through="permissions.RolePermissions", ) RolePermissions: class RolePermissions(): role = models.ForeignKey("permissions.Role", on_delete=models.PROTECT) permission = models.ForeignKey("permissions.SitePermission", on_delete=models.PROTECT) SitePermissions: class SitePermissions(): permission = models.CharField(max_length=64) ForumPermissions: class SitePermissions(): permission = models.CharField(max_length=64) forum = models.ForeignKey( "forums.forum", db_column="forumId", on_delete=models.PROTECT ) Problem of course, is that I can't connect multiple tables to the ManyToMany. If I was doing it in SQL, I'd have something like roles r LEFT JOIN role_permissions rp_s ON r.type = 's' and r.id = rp.role_id INNER JOIN site_permissions sp ON rp_s.permission_id = sp.id with a second set of joins for forum_permissions (I know that SQL isn't exactly right, more for example). So is there a way to accomplish this? Conditionally link to multiple tables? Or do I need to have a separate property in Role for each SitePermission and ForumPermission, and then have logic for … -
Django Custom Query/Temporary Table for Editing
The below issue may have several approaches and I'm open to any suggestions. What I'm outlining is just the crumb of a thought. I am tasked with uploading tables from one source to Snowflake. As a fun project, I am aiming to build a front end user interface that helps us pick a data source, data set and destination. There are already some pre-existing tables in Snowflake. I'd like to be able to grab the information from Snowflake, present it alongside the source system columns so that we can assure they match appropriately. I'm hoping to understand whether there is an appropriate way to handle this sort of task 'in the moment' in Django. I've been looking into temporary tables to present data but i'm having no luck. Any suggestions would be greatly appreciated. -
AttributeError: type object has no attribute '_meta'
I'm trying to follow the docs on using django-filter at https://django-rest-framework-datatables.readthedocs.io/en/latest/django-filters.html#django-filter-quickstart When I add the ExpertGlobalFilter to my ExpertViewset like so class GlobalCharFilter(GlobalFilter, filters.CharFilter): pass class ExpertGlobalFilter(GlobalFilter): name = GlobalCharFilter(lookup_expr='icontains') objectives = GlobalCharFilter(field_name='meetings__objective', lookup_expr='icontains') class Meta: model = Expert fields = '__all__' class ExpertViewSet(viewsets.ModelViewSet): queryset = Expert.objects.all().order_by("id") serializer_class = ExpertSerializer filter_backends = (DatatablesFilterBackend,) filterset_class = ExpertGlobalFilter I get the following error Environment: Request Method: GET Request URL: http://localhost:8000/api/experts/?format=datatables&draw=1&columns%5B0%5D%5Bdata%5D=id&columns%5B0%5D%5Bname%5D=&columns%5B0%5D%5Bsearchable%5D=true&columns%5B0%5D%5Borderable%5D=true&columns%5B0%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B0%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B1%5D%5Bdata%5D=name&columns%5B1%5D%5Bname%5D=&columns%5B1%5D%5Bsearchable%5D=true&columns%5B1%5D%5Borderable%5D=true&columns%5B1%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B1%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B2%5D%5Bdata%5D=objectives&columns%5B2%5D%5Bname%5D=objectives&columns%5B2%5D%5Bsearchable%5D=true&columns%5B2%5D%5Borderable%5D=true&columns%5B2%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B2%5D%5Bsearch%5D%5Bregex%5D=false&order%5B0%5D%5Bcolumn%5D=0&order%5B0%5D%5Bdir%5D=asc&start=0&length=10&search%5Bvalue%5D=&search%5Bregex%5D=false&_=1614377397193 Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.9/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/usr/local/lib/python3.9/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.9/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/usr/local/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/usr/local/lib/python3.9/site-packages/rest_framework/mixins.py", line 38, in list queryset = self.filter_queryset(self.get_queryset()) File "/usr/local/lib/python3.9/site-packages/rest_framework/generics.py", line 150, in filter_queryset queryset = backend().filter_queryset(self.request, queryset, self) File "/usr/local/lib/python3.9/site-packages/rest_framework_datatables/django_filters/backends.py", line 28, in filter_queryset filterset = self.get_filterset(request, queryset, view) File "/usr/local/lib/python3.9/site-packages/django_filters/rest_framework/backends.py", line 31, in get_filterset filterset_class = self.get_filterset_class(view, queryset) File "/usr/local/lib/python3.9/site-packages/django_filters/rest_framework/backends.py", line 60, in get_filterset_class filterset_model = filterset_class._meta.model Exception Type: AttributeError … -
Django votting a user ID which stores the user's answers to questions
I created a poll for unregistered users, now in the application each user can vote for the same option an unlimited number of times, how to make sure that a numeric ID is passed as a user ID to the API, which stores the user's answers to questions; one user can participate in any number of polls, and receive polls passed by the user with a granularity on the answers (what is selected) by the unique user ID. I hope for help, thanks models.py class Poll(models.Model): question = models.TextField() option_one = models.CharField(max_length=50) option_two = models.CharField(max_length=50) option_three = models.CharField(max_length=50) option_one_count = models.IntegerField(default=0) option_two_count = models.IntegerField(default=0) option_three_count = models.IntegerField(default=0) def total(self): return self.option_one_count + self.option_two_count + self.option_three_count views.py def home(request): polls = Poll.objects.all() context = {'polls':polls} return render(request, 'poll/home.html', context) def create(request): if request.method == 'POST': form = CreatePollForm(request.POST) if form.is_valid(): form.save() return redirect ('home') else: form = CreatePollForm() context = {'form':form} return render(request, 'poll/create.html', context) def update_vote(request, pk): patient = Patient.objects.get(id=pk) form = PatientForm(instance=patient) if request.method == 'POST': form = PatientForm(request.POST, instance=patient) if form.is_valid(): form.save() return redirect('/patients') context = {'form': form} return render(request, 'patients/f_patient.html', context) def vote(request, poll_id): poll = Poll.objects.get(pk=poll_id) if request.method == 'POST': selected_option = request.POST['poll'] if selected_option == … -
Caching django-autocomplete-light choices client-side?
Does django-autocomplete-light have a built in mechanism for caching the choices client-side ? I have about 50K options and downloading them each time affects the page loading time. If possible one that works with Select2ListView (I would rather not feed the choices from a foreign/m2m). (The way I imagine this would work is: client asks for choices, sends a checksum of the last list of choices it received. If the checksum is equal with what the server has, nothing new is downloaded.) If not, how could I go about acomplishing this ? (I am a JS/django beginer, so if possible an easy method). What files would I need to edit and what is the workflow of django-autocomplete-light ? At the moment I am thinking about dropping django-autocomplete-light, and using slimselectjs plus ajax, and making my own custom mechanism, but I'm afraid that by custom coding I'm setting myself up for a lot of pain. From what I've heard I shouldn't fight Django's way ... -
How to fetch current (MODEL1) data and save this data in another (MODEL2 ) field in django?
I have two models UserPhoto and PercentileRank.My requirement is that When new data create in PercentileRank model at that time save() fun. act specific task like that : 1) How to find average value of user_rate field related to each photo field?. 2) how to update this average value in UserPhoto model? UserPhoto model: class UserPhoto(models.Model): user = models.ForeignKey(to = User,on_delete = models.CASCADE,related_name='userPhoto') image = models.ImageField(upload_to = 'users_photos') description = models.TextField(null = True,blank=True) public_upload = models.BooleanField(default = True) pr_rank = models.IntegerField(default = 0) created_date = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s_%s' %(self.id,self.user) PercentileRank model: class PercentileRank(models.Model): user = models.ForeignKey(to = User,on_delete = models.CASCADE) user_rate = models.IntegerField(null=True,blank=True) photo = models.ForeignKey(UserPhoto,on_delete = models.CASCADE) created_date = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): super(PercentileRank, self).save(*args, **kwargs) ?????? ???? My requirement is similar like this(But it should be in in save() func.): _total = PercentileRank.objects.get(photo__id = id) pr_rank = _total.aggregate(Avg('user_rate')) _user_photo = UserPhoto.objects.get(id = id) _user_photo.pr_rank = pr_rank _user_photo.save() Please help me how can I achieve this.. In Advance TSM.. -
How does the Django-REST-Framework store the user's authentication token?
Reading the Django REST framework documentation, I understand that token authentication can be created and for a user: from rest_framework.authtoken.models import Token token = Token.objects.create(user=...) print(token.key) And then checked on a view-by-view basis. When accessing the API from the command line, the documentation shows that the Token is supplied in the header like so: curl -X GET http://127.0.0.1:8000/api/example/ -H 'Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' My question is, when going through the browsable API, how does Django already know my user token without having to supply it like in the curl command? -
Django Rest Framework - Group data by its parent tag
Django Rest Framework - Group data by its parent tag I have 3 serializers, One for tactics, one for techniques, one for sub techniques, and I'll be adding the sub techniques serializer as an explicit field to the techniques serializer. models class Tag(models.Model): _id = models.CharField(max_length=10) name = models.CharField(max_length=100) def __str__(self): return self._id def __unicode__(self): return self._id class ModelA(models.Model): _id = models.CharField(max_length=10) title = models.CharField(max_length=100) tags = models.ManyToManyField(Tag) queries = ArrayField(models.TextField(),null=True, blank=True, default=list) def __str__(self): return self._id def __unicode__(self): return self._id class ModelB(models.Model): subtitle = models.ForeignKey(ModelA, on_delete=models.CASCADE) def __str__(self): return self.subtitle serializers # serializers class TagSerializer(serializers.ModelSerializer): def to_representation(self, value): print(value) return value.name class Meta: model = Tag fields = ('name',) class QueriesSerializer(serializers.ModelSerializer): class Meta: model = ModelB fields = '__all__' class ASerializer(serializers.ModelSerializer): queries = QueriesSerializer(source='modelb_set', many=True) tag = TagSerializer(many=True) class Meta: model = ModelA fields = ('_id','title', 'tag','queries',) class EndUserSerializer(serializers.ModelSerializer): data = ?? class Meta: model = ?? fields = '__all__' I want to create a data visualization API where I need to use the results of ASerializer by their given tag in order to categorize each object into categories based on their associated tag if the object contains two tags, then it should be displayed in both . e.g … -
how to localize integer field in Django?
I'm working with Django rest framework. I have a price as a integer field for my products. I want to store the price as a Persian number. when I change the keyboard into Farsi (Persian) still it enter English number. I want to sent it as a Persian number to the front side to show it in the site. I just creating the api not the UI. setting: LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Tehran' USE_I18N = True USE_L10N = True USE_TZ = True admin panel: -
Django Ckeditor Save incomplete data from richtextfield to cookies or server
The title, in my opinion, is self-explanatory. Basically let’s say a user if filling out an ckeditor richtextfield like so: #app/models.py from django.db import models from ckeditor.fields import RichTextField class App_Model(models.Model): content = RichTextField() Now let’s say an user left the page. The content will not be saved. I want the content to be saved, whether it be cookies or to the server, so the user can come back and pickup where he left off. How would I do this, preferably in the most simplest way possible. Thanks. -
How to Activate Venv in Pycharm?
I have a simple project here, am using the virtual env of Pycharm for the project, I added all the libraries I needed ( Django, djangorest ...) but it seems nothing is recognized when I try to use them in the terminal of Pycharm, even it says that the venv is activated enter image description here -
How can I dinamically change list_view columns based on a filter in Django Admin?
How (if even possible) can I change the order of the columns in the list_display in Django admin UI based on a filter? For example, if not filter is applied, the admin list of a model shows columns A, B, C, D, E. If a specific filter is selected, then the columns displayed would change to B, C, E, A, D. If this is possible, how can I do it? Can I change the name of the columns to use custom columns device in my ModelAdmin? -
ImportError: No module named social_django.middleware
Hello I'm new to python and django. Currently I'm trying to run a project made in django 1.10.2 and python 2.7 in ubuntu 16.04. The project uses a module called python-social-auth and when I try to run the project I get the following error: python mana.py runserver Unhandled exception in thread started by <function wrapper at 0x7fb7d118a758> Traceback (most recent call last): File "/home/mauricio/.local/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/home/mauricio/.local/lib/python2.7/site-packages/channels/management/commands/runserver.py", line 39, in inner_run http_consumer=self.get_consumer(*args, **options), File "/home/mauricio/.local/lib/python2.7/site-packages/channels/management/commands/runserver.py", line 134, in get_consumer return StaticFilesConsumer() File "/home/mauricio/.local/lib/python2.7/site-packages/channels/handler.py", line 327, in init self.handler = self.handler_class() File "/home/mauricio/.local/lib/python2.7/site-packages/channels/staticfiles.py", line 18, in init super(StaticFilesHandler, self).init() File "/home/mauricio/.local/lib/python2.7/site-packages/channels/handler.py", line 177, in init self.load_middleware() File "/home/mauricio/.local/lib/python2.7/site-packages/django/core/handlers/base.py", line 80, in load_middleware middleware = import_string(middleware_path) File "/home/mauricio/.local/lib/python2.7/site-packages/django/utils/module_loading.py", line 20, in import_string module = import_module(module_path) File "/usr/lib/python2.7/importlib/init.py", line 37, in import_module import(name) ImportError: No module named social_django.middleware being that I already have the python-social-auth module installed. Hopefully you can help me in detail to solve this problem because as I told you I am new to using these tools. -
How to upload Images to a Webserver with React Native
So I am using React Native and trying to build a kind of socialmedia. You have to give a name, age, and so on. Now I also want to add a feature, where the user can pick a profileimage. To get name, age, and so on to the Server I use a simple HTTP POST request, but how can I upload images to my webserver from React Native/Javascript. I also use Django as the backend, but that shouldn't be that relevant :)