Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
getting logfile error permission denied . what does it mean?
I am getting below error when I run the command python3 manage.py makemigrations When I tried on my local system then also I was getting same error but when I delete logs/logfile and create new then I works good for me. Now When I tried on my server console then I got below Error (app-env) chalil@ip-172-31-5-73:~$ python3 manage.py migrate Traceback (most recent call last): File "/usr/local/lib/python3.6/logging/config.py", line 558, in configure handler = self.configure_handler(handlers[name]) File "/usr/local/lib/python3.6/logging/config.py", line 731, in configure_handler result = factory(**kwargs) File "/usr/local/lib/python3.6/logging/handlers.py", line 150, in __init__ BaseRotatingHandler.__init__(self, filename, mode, encoding, delay) File "/usr/local/lib/python3.6/logging/handlers.py", line 57, in __init__ logging.FileHandler.__init__(self, filename, mode, encoding, delay) File "/usr/local/lib/python3.6/logging/__init__.py", line 1031, in __init__ StreamHandler.__init__(self, self._open()) File "/usr/local/lib/python3.6/logging/__init__.py", line 1060, in _open return open(self.baseFilename, self.mode, encoding=self.encoding) PermissionError: [Errno 13] Permission denied: '/webapps/app/logs/logfile' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/webapps/app/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/webapps/app/lib/python3.6/site-packages/django/core/management/__init__.py", line 325, in execute settings.INSTALLED_APPS File "/webapps/app/lib/python3.6/site-packages/django/conf/__init__.py", line 79, in __getattr__ self._setup(name) File "/webapps/app/lib/python3.6/site-packages/django/conf/__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "/webapps/app/lib/python3.6/site-packages/django/conf/__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/local/lib/python3.6/importlib/__init__.py", line 126, in … -
Cannot assign "(<department: department object (1)>,)": "internal_information.department" must be a "department" instance
i used postman to create and update model data , my create function can work but my update cant, i get a error "Cannot assign "(<department: department object (1)>,)": "internal_information.department" must be a "department" instance." my_api_view_createmy_api_view_updatemy_modelmy_serializermy_error -
Is possible Django CRUD operation without using model forms?
I am creating a Registration app in django where I want to update user info after login. I am using bootstrap forms. Is possible Django CRUD operation without using model forms? I created user like this: def handleRegister(request): if request.method == 'POST': username = request.POST['username'] fname = request.POST['fname'] lname = request.POST['lname'] email = request.POST['email'] pass1 = request.POST['pass1'] pass2 = request.POST['pass2'] # check erronous inputs if len(username) > 10: messages.error(request, "Username should be less than 10 chracters") return redirect('/') if pass1 != pass2: messages.error(request, "Passwords do not match") return redirect('/') if not username.isalnum(): messages.error(request, "Username should be alphanumeric") return redirect('/') # creating user here myuser = User.objects.create_user(username, email, pass1) #creating user with the help of User(you have to import it. from django.contrib.auth.models import User) myuser.first_name = fname myuser.last_name = lname myuser.save() # saving created user messages.success(request, "Your account has been created sucessfully") return redirect('/') else: return HttpResponse("404 not found") is there any method like above where I can update user info? -
Why does my website keep on having Privacy issue?
Does anyone know the reason for Privacy Issue? But it only happens on my website url without the ("www").For example, when accessing the url https://mywebsite.com, it shows the "Your connection is not private" sometimes. But my SSL certificate is still valid and not yet expired. But when I access the full url, https://www.mywebsite.com, there is no privacy issue. I hope someone can help me. Thank you. -
Getting the value of select option Django
Im been having a trouble how can I get the the value of my select option, I been using javascript to set the value of select option, below is my code which is returning the province value to number instead of text. The problem is how can I convert the number to text, is there any expert who share solution about this. views.py def sample_data(request): if request.method=='POST': province = request.POST['list1'] print(province) #return ex. 2 depend on select value return render (request,'sample.html') Select option - my reference link <select id="list1" name ="list1" onchange="updateList('list2', this);"></select> <select id="list2" name ="list2" onchange="updateList('list3', this);"></select>> <select id="list3" name ="list3"></select> javascript let data = [{"id":1,"name":"USA","parentid":0}, {"id":2,"name":"Japan","parentid":0}, {"id":3,"name":"Europe","parentid":0}, {"id":4,"name":"California","parentid":1}, {"id":5,"name":"Oklahoma","parentid":1}, {"id":6,"name":"Arizona","parentid":1}, {"id":7,"name":"Kantô","parentid":2}, {"id":8,"name":"Kansai","parentid":2}, {"id":9,"name":"Chügoku","parentid":2}, {"id":10,"name":"France","parentid":3}, {"id":11,"name":"Deutschland","parentid":3}, {"id":12,"name":"Espana","parentid":3}, {"id":13,"name":"Sacramento","parentid":4}, {"id":14,"name":"Los Angeles","parentid":4}, {"id":15,"name":"San Diego","parentid":4}, {"id":16,"name":"Tulsa","parentid":5}, {"id":17,"name":"Oklahoma City","parentid":5}, {"id":18,"name":"Lawton","parentid":5}, {"id":19,"name":"Phoenix","parentid":6}, {"id":20,"name":"Flagstaff","parentid":6}, {"id":21,"name":"Tucson","parentid":6}, {"id":21,"name":"Tokyo","parentid":7}, {"id":22,"name":"Chiba","parentid":7}, {"id":23,"name":"Tochigi","parentid":7}, {"id":24,"name":"Kyoto","parentid":8}, {"id":25,"name":"Osaka","parentid":8}, {"id":26,"name":"Nara","parentid":8}, {"id":27,"name":"Tottori","parentid":9}, {"id":28,"name":"Hirochima","parentid":9}, {"id":29,"name":"Okayama","parentid":9}, {"id":30,"name":"Quimper","parentid":10}, {"id":31,"name":"Toulouse","parentid":10}, {"id":32,"name":"Nancy","parentid":10}, {"id":33,"name":"Dusseldorf","parentid":11}, {"id":34,"name":"Leipzig","parentid":11}, {"id":35,"name":"Munchen","parentid":11}, {"id":36,"name":"Barcelona","parentid":12}, {"id":37,"name":"Sevilla","parentid":12}, {"id":38,"name":"Guernica","parentid":12}] function populateList(list, pid) { let l = document.getElementById(list); l.innerHTML = ""; let topItem = document.createElement("option"); topItem.value = 0; topItem.text = "--Select--"; l.appendChild(topItem); let items = data.filter(item => item.parentid == pid); items.forEach(function(item){ let newItem = document.createElement("option"); newItem.value = item.id; newItem.text = item.name; l.appendChild(newItem); }) } function updateList(selList, thisList) { if (thisList.value != … -
Django: Select from the dropdown the object that has the field is_active=True
i'm a newbie using django and i have a problem that cannot solve. In my ServiceCreateView i need to select from the dropdown the object car that has the field is_active = true, how can i acomplish that? class Car(models.Model): brand = models.charfield(...) is_active= models.BooleanField(default=True) class Service(models.Model): car = models.ForeingKey('Car'....) name = models.Charfield() class ServiceCreateView(CreateView): model = Service form = ServiceForm ... If i change the field is_active to false in Car model, should not be shown in the dropdown. can someone put me in the right direction? -
Errors when passing a list through URL in Django
I try to pass a list through an URL in Django. I found this: Passing a list through url in django But I still get Errors. I feel like Iam running in a circle. My urls: path('query/', include(('query.urls', 'query-space'), namespace='query-space')), re_path(r'^2/(?P<amb_list>\w+)/$',views.ambitionGenPage, name='userambitiongen'), My views: def ambitionPage(request): if request.method == 'POST': form = AmbitionForm(request.POST) if form.is_valid(): ambs_list = form.cleaned_data['ambition_field'] redirect = HttpResponseRedirect(reverse('query-space:userambitiongen')) redirect['Location'] += '&'.join(['ambs={}'.format(x) for x in ambs_list]) return redirect form = AmbitionForm() return render(request, 'query/ambition.html',{'form':form,}) def ambitionGenPage(request): ambitions = request.GET.getlist('amb_list') if ambitions: ambitions = [int(x) for x in ambitions] print(ambitions) #I first want to check what data I get return render(request, 'query/ambitionGen.html',{}) I adapted the code of the link. In the line: redirect = HttpResponseRedirect(reverse('query-space:userambitiongen', args=(amb_list))) he doesnt know the argument: NameError: name 'amb_list' is not defined In the example there is no argument. When I try this I get the error: Reverse for 'userambitiongen' with no arguments not found. 1 pattern(s) tried: ['query/2/(?P<amb_list>\\w+)/$'] I also found nothing in the internet to this expression: redirect['Location'] Could someone explain to me what ['Location'] stands for? What would be the right solution? I tried to find it by myself in many hours. Thank you very much for your time! -
Django save() method won't save my forms and can't create a new instance
I want to save 2 forms in my django view: def create_model(request): context = { 'form_one' : Register_modelOne(prefix = 'form_one'), 'form_two' : Register_modelTwo(prefix = 'form_two'), } if request.method == "POST": form_one = Register_modelOne(request.POST, prefix = 'form_one') form_two = Register_modelTwo(request.POST, prefix = 'form_two') if form_one.is_valid() and form_two.is_valid(): form_one.save() form_two.save() ParentModel.objects.create(name = 'mymodel', element_one = form_one, element_two = form_two) The whole point is to create a new ParentModel which has a manyToMany() relation with both modelOne and modelTwo. But Django won't save it in my database this way. Does anyone have any idea why? (also even form_one and form_two are not saved in the database with this method) note: This is connected to my question in Another Question -
Django template - How to get key, value(list) from a dictionary in the request context
I have my context in a html template and I'm not able to read the value which is a List of objects from key in my dictionary. This is my context: {'month_posts': defaultdict(<class 'list'>, {'October': [<Post: Set pagination>, <Post: Test pagination>], 'November': [<Post: Redesign Model>]} ) } This is the for loop I'm implementing to get the key and value: {% for month, posts in month_posts.items %} ... <h3>{{ month | capfirst }}</h3> {% for post in month_posts[month] %} <a href="#">{{ post.title }}</a> {% endfor %} ... {% endfor %} I got this error: Could not parse the remainder: '[month]' from 'month_posts[month]' I have tried these: {% for month in month_posts %} I got no errors but also no data in my template. Do you have any idea how I could get the List in the value of the Dictionary? Thanks. -
Not able to insert data into database using Django
I am a beginner in Django and I am trying to insert values into the auth_user table. But somehow I am not able to do so. I tried to resolve but everything seems to go in vain. Here is my views.py: from django.shortcuts import render,redirect from django.contrib.auth.models import User, auth # Create your views here. def register(request): if request.method == 'POST' : firstname = request.POST['firstname'] lastname = request.POST[ 'lastname'] emailid= request.POST['emailid'] username= firstname+lastname passwordl = request.POST['password'] user = User.objects.create_user(username=username,first_name=firstname,last_name=lastname) user.save() return redirect('admin/') else: return render(request, 'employee/register.html') This the urls.py from django.urls import path from . import views urlpatterns = [ path('register/', views.register, name='register'), ] I can also notice than when I click register button I get an error that employee\register\register was called which doesnt exist, which is strange as employee\register is to be fetched. -
How to pass currently user ID/PK from view to form in Django?
The problem I'm having is I'm trying to create a form which passes the currently logged-in users ID by embedding it within a hidden field in a ModelForm. Models.py class UserPhotos(models.Model): user = models.ForeignKey(NewUser, on_delete=models.CASCADE) #photos = models.ImageField(height_field=1350, width_field=1080) description = models.CharField(max_length=200) date = models.DateTimeField(auto_now=True) class Meta: '''Change plural name''' verbose_name_plural = 'Photos' Forms.py class AddPhotos(forms.ModelForm): user = forms.CharField(widget = forms.HiddenInput(), required=False) class Meta: model = UserPhotos fields = ( 'description','user', ) Views.py def add_photo(request): context = {} user = request.user if not user.is_authenticated: return redirect('my_app:login',) if request.POST: form = AddPhotos(request.POST) if form.is_valid(): form.save(commit=False) form.user=request.user form.save return redirect('/') else: context['photoAdd_form'] = form else: form = AddPhotos() context['photoAdd_form'] = form return render(request, 'main/photo_add.html', context) I have tried something like this It's works, but I have no idea how to pass the ID to the init. It gave me a error : KeyError at /add 'userID' Forms.py ... def __init__(self, *args, **kwargs): #It is works but how will i pass the data request = kwargs.pop('userId') print(request) super(AddPhotos, self).__init__(*args, **kwargs) self.fields['user'].initial = request.user Views.py def add_photo(request): context = {} user = request.user if not user.is_authenticated: return redirect('my_app:login',) if request.POST: form = AddPhotos(request.POST, userId = request.user.id) ... -
django autotranslate gives an error "IndexError:list index out of range"
I have configured django autotranslate as per the direction on the pypi page but when I try to run the translate_messages command, it throws back an error return lambda: self._basic_translate(text, target_language, source_lauguage)[0] File "C:\Users\Richards\AppData\Local\Programs\Python\Python38\lib\site-packages\goslate.py", line 253, in _basic_translate data = {'src': raw_data[-1][0][0]} IndexError: list index out of range I dont have have a explicit list in my project, just querysets and its quite numerous. please help me on this -
Redirect Reverse to specific view with arguments
In the same app, I have a form that can be rendered and processed in two different views. The url for the views are defined as following: app_name = 'table' urlpatterns = [ path('<int:table_pk>/order/', include([ path('', views.table_detail_category_view, name='table_detail_category_view'), path('<str:menu_category>/', views.table_detail_item_view, name='table_detail_item_view'), ])), ] The processing of the form, however, is implemented in only one of the views (for eg. table_detail_category_view) since it is redundant to implement one more time (one for each view). After processing the form, I have to redirect the page to whatever view that was displayed before. Specifically, I am looking for something like this: if request.method == 'POST': ...process form... if previous_view = table_detail_category_view: return redirect(reverse('table:table_detail_category_view', args=(table_pk,))) else: if previous_view = table_detail_item_view: return redirect(reverse('table:table_detail_item_view', args=(table_pk, category,))) The variables table_pk and category are present in both views. I am trying to avoid implementing the form-processing twice (one in each view) in order to redirect reverse to the appropriate view. That method does not seem DRY. Thanks. -
How to use async with Mutation in Django-graphene
I have a problem, where I want to optimise a client call to a mutation in a GraphQL API. The mutation executes 2 methods, where one is slow and where the result does not need to be send back to the client. I have tried to look at Django signals to handle this, but since signals are executed in sync, there is no benefit. Also, using Django signal request_finished seems not possible, because the method I need to execute needs to access model instance. So my question is this. Lets say I have a Django Model and I have two methods I use in a mutation. class My_model(models.Model): some_field = models.CharField() def some_method(): return "do something" def some_other_method(): return "do something else" Now I have a mutation like the one below, where I do not want the client to wait for the execution of the method My_model.some_other_method() class CreateTwoObjects(graphene.Mutation): result = graphene.String() def mutate(self, info, input): result = My_model.some_method() # method to not wait for My_model.some_other_method() return CreateTwoObjects(result = result) Is there a way I can execute this method in async and not have client wait for the return? -
Displaying only linked tags Django Admin
i have product tag and its variations of tag example: Color|green Quality|bad i need to display only linked variations when i create product i need to display only colors when i choice color models.py class Variety(models.Model): varietyName = models.CharField(max_length=30) def __str__(self): return self.varietyName class Meta: verbose_name = "List variations" class Tag(models.Model): STATUS_VARIETY=( ('Filters', 'Filter'), ('Variaty', 'Variaty'), ('Boths', 'Boths'), ) status = models.CharField(max_length=10, choices=STATUS_VARIETY, default='Boths', verbose_name='status') name = models.CharField(max_length=255, verbose_name='name') variety = models.ManyToManyField(Variety, related_name='children', verbose_name='Parent') def __str__(self): return self.name class Meta: verbose_name = "Variation" verbose_name_plural = "Variations" class Productcopy(models.Model): STATUS_PRODUCT=( ('Publish', 'Publish'), ('Not_to_publish', 'Not_to_publish'), ) status = models.CharField(max_length=30, choices=STATUS_PRODUCT, verbose_name='status') name = models.CharField(max_length=100, verbose_name='name') tag = models.ForeignKey(Tag, verbose_name='Variation', on_delete=models.CASCADE) variety = models.ManyToManyField(Variety, verbose_name='Variations') def __str__(self): return self.name class Meta: verbose_name = "product" verbose_name_plural = "products" admin.py from .models import * class TagAdmin(admin.ModelAdmin): list_display = ('name', 'status',) filter_horizontal = ('variety',) class ProductcopyAdmin(admin.ModelAdmin): list_display = ('name', 'status',) filter_horizontal = ('variety',) admin.site.register(Tag,TagAdmin) admin.site.register(Productcopy,ProductcopyAdmin) admin.site.register(Variety) -
Django on Apache2: Issue in.conf-file?
Good day to all of you, together with our admin in our company, we're trying to deploy Django on Apache2 together with mod_wsgi, but we're facing some minor issues. I'm hoping, some of you might help and take a look at the following lines!? Right now, the directory on our server is looking like this: ./var/www/ |-- myproject |-- manage.py |-- project/ |-- __init__.py |-- settings.py |-- urls.py |-- wsgi.py |-- statics |-- venv When I'm trying to open the site, it just keeps on loading but nothings gonna happen! I'm wondering wether the data inside our .conf-file might be wrong! <VirtualHost *:80> . . . Alias /static /var/www/myproject/static <Directory /var/www/myproject/static> Require all granted </Directory> <Directory /var/www/myproject/project> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-path=/var/www/myproject python-home=/var/www/myproject/venv WSGIProcessGroup myproject WSGIScriptAlias / /var/www/myproject/project/wsgi.py </VirtualHost> If I understood it correctly, the "python-home" inside the "WSGIDaemonProcess" should point onto my Virtual Environment to collect the necessary components and the "python-path" onto my project!? I also noticed, that the current running python-version on the server is 2.7.6, although my admin installed version 3.7. The installed mod_wsgi is "libapache2-mod-wsgi-py3" for python 3x! Could this also be a problem? Thanks and a great day to … -
In S3 Bucket CORS Configrations not allowing xml and asking for json instead
In S3 Bucket CORS Configrations not allowing "XML" and asking for "Json" instead <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <AllowedMethod>POST</AllowedMethod> <AllowedMethod>PUT</AllowedMethod> <AllowedHeader>*</AllowedHeader> </CORSRule> </CORSConfiguration> Was Working earlier but now it is giving me this error "The CORS configuration must be written in valid JSON." Some Changes are made in "Amazon S3 Bucket" by AMAZON , Please give me json of this to add in CORS ? -
Djnago 'ImageFieldFile' object has no attribute '_meta'
Actually i'm trying to update user profile but when i try to update it it show's the error. AttributeError at /user/profile/ 'ImageFieldFile' object has no attribute '_meta' After searching so many solution i can't get rid of it. I am messing with my code from 24hrs. Please help me to get rid of this. -- My code is --- Views.py @login_required() def profile(request): if request.method=='POST': u_form = UserUpdateForm(request.POST,instance=request.user) p_form = ProfilePicUpdateForm(request.POST,request.FILES,instance=request.user.profile_image) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Account Created Successfully for {username}') redirect('profile/') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfilePicUpdateForm() context = {'u_form': u_form,'p_form':p_form} return render(request,'profile.html',context) Forms.py class UserUpdateForm(forms.ModelForm): username = forms.CharField() email = forms.EmailField() first_name = forms.CharField() last_name = forms.CharField() class Meta: model = KeepSafeUserModel fields = ['username','email','first_name','last_name'] class ProfilePicUpdateForm(forms.ModelForm): class Meta: model = KeepSafeUserModel fields = ['profile_image'] Models.py from django.db import models from django.contrib.auth.models import User from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) # ///////////////User Manager///////////////////// # Create your models here. # overriding the create and superuser function class MyAccountManager(BaseUserManager): def create_user(self,email,username,password=None): if not email: raise ValueError("Users Must Have email Address") if not username: raise ValueError("Users Must Have username") user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,email,username,password): user = self.create_user( email = self.normalize_email(email), … -
Foreign key value in Django REST Framework Datatables
I followed this SOF question Foreign key value in Django REST Framework closely and many others plus read this documentation and similar multiple times https://datatables.net/manual/tech-notes/4 but have yet to find a solution. Error message: DataTables warning: table id=entrytable - Requested unknown parameter 'symbol' for row 0, column 9. For more information about this error, please see http://datatables.net/tn/4 However, the right symbol.name does work in the end when I click okay on the error message.. I've tried to find a solution for this error for the past 2 days and not sure what else to try. If I comment out: # symbol = serializers.CharField(source='symbol.name', read_only=True) Then the serializer will show just the foreign key but no error message. Seems to be an issue in my datatables javascript now. However, I've tried their suggestions and still no luck. serializers.py (Everything commented out in serializers.py are attempted solutions) class EntrySerializer(serializers.ModelSerializer): symbol = serializers.CharField(source='symbol.name', read_only=True) # symbol = serializers.SerializerMethodField('get_symbol_name') # # def get_symbol_name(self, obj): # return obj.symbol.name class Meta: model = Entry # fields = ('id', 'date', 'amount', 'price', 'fee', 'entry_type', 'reg_fee', 'transaction_id', 'trade', 'symbol', 'created_by') fields = '__all__' # depth = 1 entry_list.html {% extends "dashboard/base.html" %} {% load i18n %} {% block … -
Deploy Django project to Ubuntu + Apache + mod_wsgi
Please please please help me. I've followed this tutorial and this one and this one and this but still can't make it work. I have a VM from DigitalOcean with Apache and mod_wsgi. My Django project is stored in /var/www/mydomain.com. It is nothing fancy, just a Hello World. All I want is to run that with mod_wsgi in Daemon mode. Please tell me what should I put in my config file? All those tutorials I read provide a different approach and none of them worked for me. At best, I got the famous index of showing the content of the folder. So I removed everything. In fact I destroyed my droplet and now its a fresh install of Ubuntu 20.04. Apache is installed and works. Here's the config file if it matters: <VirtualHost *:80> ServerAdmin webmaster@localhost ServerName mydomain.com ServerAlias www.mydomain.com DocumentRoot /var/www/mydomain.com ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined RewriteEngine on RewriteCond %{SERVER_NAME} =mydomain.com [OR] RewriteCond %{SERVER_NAME} =www.mydomain.com RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] </VirtualHost> The last 4 lines are added by certbot to redirect http to https, and it works fine. -
Django version 3.1.3 form not saving to model
I am following this tutorial I have gone back and written the code to match exactly. I have another form that works called category_add which is exactly the same as this form. But for the life of me I cannot figure out why bookmark_add doesn't update the database with the form entries. Models.py from django.db import models from django.contrib.auth.models import User class Category(models.Model): title = models.CharField(max_length=255) description = models.TextField(blank=True, null=True) created_by = models.ForeignKey(User, related_name='categories', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'Categories' def __str__(self): return self.title class Bookmark(models.Model): category = models.ForeignKey(Category, related_name='bookmarks', on_delete=models.CASCADE) title = models.CharField(max_length=255) description = models.TextField(blank=True, null=True) url = models.CharField(max_length=255, blank=True) created_by = models.ForeignKey(User, related_name='bookmarks', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title View.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from .forms import BookmarkForm @login_required def bookmark_add(request, category_id): if request.method == 'POST': form = BookmarkForm(request.POST) if form.is_valid(): bookmark = form.save(commit=False) bookmark.created_by = request.user bookmark.category_id = category_id bookmark.save() return redirect('category', category_id=category_id) else: form = BookmarkForm() context = { 'form': form } return render(request, 'bookmark/bookmark_add.html', context) Forms.py from django.forms import ModelForm from .models import Bookmark class BookmarkForm(ModelForm): class Meta: model = Bookmark fields = ['title', 'description', 'url'] Urls.py path('', dashboard, name='dashboard'), path('categories/', categories, name='categories'), path('categories/add/', … -
Django Filling an Empty Query Set
In my Django Application, I have printed a list of query's. the first query set contains the followers of the current logged in user, The second is an empty query set, and the last printed items are a list of queries each containing the profile objects of each of those followers indicated in the first printed query. Is there a way to fill the empty query set in the middle with the list of profile object query sets, but all in one ( similar to the format of the first printed query set) -thank you for taking the time to read my questionenter image description here -
whats the best possible way to sort here
In my django app i have an import model where i have FOR_COUNT as a field and VALUE as another field in my views i am trying to show top five countries(countries with highest values) and all the remaining countries as one entity i.e others. What will be the best possible way to do this, i think sorting of some kind will work here, but am fairly new with django. Country = Import.objects.order_by('FOR_COUNT').values('FOR_COUNT').distinct() result = [] for val in Country: Info = Import.objects.filter(FOR_COUNT=val['FOR_COUNT']).filter(Date__year=year) TotalValue = Info.aggregate(Sum('VALUE')) result.append({ "label" : val['FOR_COUNT'], "value" : 0 if TotalValue['VALUE__sum'] is None else TotalValue['VALUE__sum'] }) return_data.update({ "topCounty" : result }) -
Django Rest Framework logic
My project receives a POST with a string and then I want to run a function that may take several seconds to finish on that query and update the model with the result. Currently I'm using Django Rest Framework to create an API that creates the model from the POST request and I put the function call within the views.py as so: def post(self, request, format=None): serializer = SearchSerializer(data=request.data) if serializer.is_valid(): query = serializer.validated_data.get('query') # I would expect ProteinSearch.search(query) to take a long time protein_search = ProteinSearch.search(query) serializer.save(**protein_search) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) This clearly is blocking at the moment. My question is, do I have this in the right place and should be using some type of concurrency such as threads or is this incorrectly placed in views? -
Unresolved Reference in Pycharm Using Django
code I'm using Pycharm. I created a new app called pages that's part of this tutorial on Youtube. I created some functions in the pages/views.py. Then I went to urls.py to import the functions and add the URLs. But the IDE can't find pages. I tried restarting Pycharm/invalidating the caches, and that did not work. Please let me know if you have any ideas.