Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make search in Django with SearchVector on ArrayField?
I have a Company model with related tags. I need to configure search by name, content and tags, and if search works with name, content fields , it doesn't on ArrayField -> tags models.py class Company(models.Model): name = models.CharField(max_length=150) content = models.TextField(blank=True) **tags** = ArrayField(models.CharField(max_length=200), blank=True, null=True utils.py def get_rank_search_result(q, category=None): ... vector = SearchVector('name', config='russian', weight='A') + \ SearchVector('content', config='russian', weight='B') + \ SearchVector('tags', config='russian', weight='B') #SearchVector(Func(F('tags'), Value(' '), function='array_to_string'), config='russian', weight='B') #doesn't work either query = SearchQuery(q, config='russian', search_type=search_type) return list(qs.annotate(rank=SearchRank(vector, query)).filter(rank__gte=0.3).order_by('-rank')) ``` Actually, the search stops working after i add line with SearchVector('tags').... -
Edit a unique field used as foreignkey in Django
I have two models, one Price and Market: class Market(models.Model): market_name = models.CharField(max_length=3, unique=True) class Price(models.Model): market = models.ForeignKey(Market, on_delete=models.CASCADE, to_field="market_name") I want to be able to edit the market_name field on the Market model and have the subsequent Price objects updated without causing errors. update or delete on table "appname_market" violates foreign key constraint "appname_price_market_id_5f75a816_fk_appnames" on table "appname_price" DETAIL: Key (market_name)=(Cute Martket Name) is still referenced from table "appname_price". Pointing them on the pk is one the solution, but I want to stick to using market_name as foreignkey for a reason. How would you do that ? I imagined a method for pre_save : @receiver(pre_save, sender=Market) def update_market_field(sender, instance, *args, **kwargs): try: obj = sender.objects.get(pk=instance.pk) except sender.DoesNotExist: pass # Object is new, so field hasn't technically changed, \ # but you may want to do something else here. else: if not obj.market_name == instance.market_name: # Field has changed Price.objects.filter(market=obj.market_name).update_or_create(market=instance) But this still producing errors because actually the Market object hasn't been saved yet. A half solution also is to delete all Prices with that obj.martket_name in this pre_save method, and I have seen that it effectively update the unique field but ... -
If a user uploads an infected file but my Django server does not write it to disk, is my server still at risk?
In the Django docs, it mentions that image uploads below 2.5MB are not written to disk, just to memory. I just need my server to process these images. My concern though, is it possible for my server to still get infected despite not writing them to disk? -
i made an extra Template Tag and it bring a problem for me
Guys I already made an init.py for this to make this as a module so that's not the error from django import template from markdownx.utils import markdownify register = template.Library() @register.filter(name = 'markdown') def markdown(text): return markdownify(text) <p>{{ blog.| markdown |safe }}</p> This not giving any error to me but when I write a blog then on the webpage it is not showing anything, means for which I used markdown template tag, so please help me if you can. -
How do I resolve a 403 error upon accessing site with django?
The site is running on a vps with CentOS7. The server is using the latest version of httpd (apache2 for centos) and mod-wsgi. The website was made with django. Every time I try to access the site either through the ip I get a 403 forbidden error and when I try the site's domain I get a timed out error. sudo status httpd returns Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled) Active: active (running) since Wed 2020-04-29 01:44:44 MST; 1s ago Docs: man:httpd(8) man:apachectl(8) Process: 3698 ExecStop=/bin/kill -WINCH ${MAINPID} (code=exited, status=0/SUCCESS) Process: 29778 ExecReload=/usr/sbin/httpd $OPTIONS -k graceful (code=exited, status=0/SUCCESS) Main PID: 3703 (httpd) Status: "Processing requests..." CGroup: /system.slice/httpd.service ├─3703 /usr/sbin/httpd -DFOREGROUND ├─3704 /usr/sbin/httpd -DFOREGROUND ├─3705 /usr/sbin/httpd -DFOREGROUND ├─3706 /usr/sbin/httpd -DFOREGROUND ├─3707 /usr/sbin/httpd -DFOREGROUND ├─3708 /usr/sbin/httpd -DFOREGROUND └─3709 /usr/sbin/httpd -DFOREGROUND This is my sites config file stored in /etc/httpd/conf.d/mysite.com.conf # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value … -
Error in models, TypeError: on_delete must be callable
When I run the following command: python manage.py makemigrations I have this error: File "/home/user/project/myvirt/forum/boards/models.py", line 9, in <module> class Topic(models.Model): File "/home/user/project/myvirt/forum/boards/models.py", line 12, in Topic board = models.ForeignKey(Board, related_name='topics', on_delete='cascade') File "/usr/local/lib/python3.7/dist-packages/django/db/models/fields/related.py", line 801, in __init__ raise TypeError('on_delete must be callable.') TypeError: on_delete must be callable. My models.py content is: from django.db import models from django.contrib.auth.models import User # Create your models here. class Board(models.Model): name = models.CharField(max_length=30, unique=True) description = models.CharField(max_length=100) class Topic(models.Model): subject = models.CharField(max_length=255) last_updated = models.DateTimeField(auto_now_add=True) board = models.ForeignKey(Board, related_name='topics', on_delete='cascade') creator = models.ForeignKey(User, related_name='topics', on_delete='cascade') class Post(models.Model): message = models.TextField(max_length=4000) topic = models.CharField(Topic, related_name='posts', on_delete='cascade') created_by = models.CharField(User, related_name='posts', on_delete='cascade') created_at = models.DateTimeField(auto_now_add=True) updated_by = models.CharField(User, related_name='posts', on_delete='cascade') updated_at = models.DateTimeField(null=True) This is an exercise in sample forum and seems to be a problem with on_delete='cascade'. -
Django admin reset search box query on filter selection
I have the following class in Django admin of a model: class TopUpsAdmin(admin.ModelAdmin): search_fields = ('user__email', 'user__phone_number',) list_filter = ('status',) Currently the default behavior of the filter is if search box in the listing page is input with test_1 which is a user name and search up the result(url will have the following parameter /?q=test_1) , if select an option in the filter then the filter results also got affected by the search box query on the URL ?q=test_1&status__exact=1) I would like to not have the search results filter the list when i choose a filter. Reading Django docs only provide me how to override the filter with existed query in the parameter(which come from search box). Any help would be appreciate -
how to return several FileField from Queryset in Django?
I have a models with FileField for videos. When i upload only one video i can return it with this code in the view.py: def cours(request, id, slug): c = Cours.objects.get(id=id, slug=slug) p = Plan_simple.objects.filter(cours=c) return render(request, 'upload/cours.html', locals()) But when i upload two or more videos whith formset, and i change get fuction by filter it doesn't work: def cours(request, id, slug): c = Cours.objects.get(id=id, slug=slug) p = Plan_simple.objects.filter(cours=c) return render(request, 'upload/cours.html', locals()) the models.py class Cours(models.Model): titre = models.CharField(max_length=100) slug = models.SlugField(max_length=100) auteur = models.CharField(max_length=42) comment = models.TextField(null=True) link = models.CharField(max_length=100) date = models.DateTimeField(default=timezone.now, verbose_name="Date de parution") categorie = models.ForeignKey('Categorie', on_delete=models.CASCADE) def save(self, *args, **kwargs): self.slug = slugify(self.titre) super(Cours, self).save(*args, **kwargs) class Meta: verbose_name = "cours" db_table = "cours" ordering = ['date'] class Plan_simple(models.Model): partie = models.CharField(blank=True, max_length=100) date = models.DateTimeField(default=timezone.now, verbose_name="Date de parution") vid = models.FileField(upload_to='file/', blank=True, null = True) cours = models.ForeignKey(Cours, related_name = "plan_simple", on_delete=models.CASCADE) def __str__(self): return self.partie class Meta: db_table = "plan_simple" Can you help me? Thanks -
Django JsonField Lookup Filtering with an unknown subkey
I want to filter a Django model by the value of a nested JSON field key when I don't know one of the key values. E.g. I want to do: Model.objects.filter(json_field__firstKey__{UNKNOWN_ID_KEY}__desiredKey__in=[OPTION1,OPTION2]) so that whenever this nested structure exists, and desiredKey exists, I can filter by the desiredValue being OPTION1 or OPTION2 i.e. {desiredKey: OPTION1} or {desiredKey: OPTION2}. I have not managed to find documentation supporting this. Is this possible? If not, does anybody have any alternavtive suggestions? -
Django combine two querysets
My model: class Renewal(models.Model): policy_number = models.integerField() invitation_date = models.DateTimeField() Snapshot of my table is as follows id policy_number invitation_date 86 4353 2020-04-21 16:37:39.071941 87 4354 2020-04-21 16:38:16.082238 97 4355 2020-04-21 17:18:03.997882 99 4377 2020-04-21 17:26:58.414530 162 4218 2020-04-22 18:42:23.066879 167 4218 2020-04-22 18:29:10.571033 171 4218 2020-04-22 18:39:17.546550 175 4238 2020-04-23 17:35:54.444945 176 4238 2020-04-23 17:36:01.482819 177 4239 2020-04-23 17:42:15.056850 178 4238 2020-04-24 13:00:06.886101 179 4243 2020-04-24 13:00:32.098504 180 4241 2020-04-24 13:21:31.215547 181 4360 2020-04-29 13:48:18.765400 in my views, I'm trying to get policy_number in a given date range, as follows def some_function(request): start_date = datetime.date.today() end_date = start_date - datetime.timedelta(days=5) renewals = Renewal.objects.filter(invitation_date__gte=star_date, invitation_date__lt=end_date) print(renewals) what i'm getting : [4238, 4243, 4241] expected answer : [4238, 4243, 4241, 4360] this should ideally give me all renewal records created in last 5 days. However, if today is 2020-04-29, the last policy record should have been 4360, but my last policy record is 4241 -
Django :Redirect to a url which having parameters in it through other template
I wanna to redirect to a url which having parameters in it through other webpage from database like I have homepage and a button on it when click on it then it render a page details with parameters through home page from database in it And on detailpage also have a button With name show and i want when i click on the show button then it again redirects me to the page detailpage but it shows me no reverse found and then parameter arguments id -
python list.append() problem when storing class objects
I have a problem when the some class objects are going to be added to the list in a loop process. let's say I have a database [ 'kid' , 'parent' , 'grandfather' ] with many records. i have a class: class Person: name children grandchildren I make a loop (I know it's a bad idea and that I can simply use queries) and look for every grandfather. an instance of class stores the data of every grandfather and at the end is appended to a list called Persons_List. Here is the Code: p = Person() Persons_List = list() pr = "" #parents gr = "" #grandfather for i in my_database.objects.all().order_by('grandfather'): if gr != i.grandfather: gr = i.grandfather pr = i.parent if p.name !="": Persons_List.append(p) # [:] raises Error and deepcopy not working p.name = "" p.parents.clear() p.grandchildren.clear() p.name = i.grandfather p.children.append(i.parent) p.grandchildren.append(i.kid) else: if pr != i.parent: pr = i.parent try: p.children.remove(pr) except: None p.children.append(pr) p.grandchildren.append(i.kid) Persons_List.append(p) #Adds The Last p To The List the problem is that in the end the Data Stored in list is wrong and messy. the name is the last p.name. and the children and grandchildren are wrong. -
user foreign key in Django
I have written a view that let me store some datas in a database: def save(request, product_id): product = Product.objects.get(pk=product_id) user = request.user p = SavedProduct(username= user, product_off_id=product.off_id) p.save() This is my models: class Product(models.Model): name = models.CharField(max_length=2000) off_id = models.BigIntegerField() class SavedProduct(models.Model): username = models.CharField(max_length=2000) product_off_id = models.BigIntegerField() It does the job but I am struggling to implement a OneToOneField to username and product_off_id. I know product_off_id = models.BigIntegerField() should be product_off_id =models.OneToOneField(Product) but what should I pass in p=SavedProduct() for the product_off_id field? -
Django NoReverseMatch error with no arguments not found. 1 pattern(s) tried
I have a model which has two foreign keys as below class BatPerformance(models.Model): country = models.ForeignKey('TeamStructure', on_delete=models.CASCADE, null=True, related_name='country') player = models.ForeignKey('PlayerStructure', on_delete=models.CASCADE, related_name = 'playerbatperf') # Batting Performance Fields batting_Matches = models.IntegerField(default=0) batting_innings = models.IntegerField(default=0) batting_notouts = models.IntegerField(default=0) batting_Runs = models.IntegerField(default=0) batting_HS = models.IntegerField(default=0) batting_avg = models.FloatField(default=0.0) batting_ballsfaced = models.IntegerField(default=0) batting_strikerate = models.FloatField(default=0) batting_hundreds = models.IntegerField(default=0) batting_fifty = models.IntegerField(default=0) batting_twohundreds = models.IntegerField(default=0) batting_fours = models.IntegerField(default=0) batting_sixes = models.IntegerField(default=0) def __str__(self): return str(self.player) + ': ' + str(self.match) I created a form for the same with all the fields. my views.py as Below. class BatStatistics(FormView): template_name = 'form.html' form_class = NewPlayerBatStatistics success_url = '.' def form_valid(self, form): # Form is Valid new_team = form.save(commit=True) return HttpResponseRedirect(self.get_success_url()) def form_invalid(self, form): # Form is Invalid print(form.errors) return self.render_to_response(self.get_context_data(form=form)) urls.py urlpatterns = [ path('', test), path('homepage/', Index.as_view(), name = 'index'), path('teamdetails/', Teams.as_view(), name = 'teamlist'), path('fixtures/',Fixtures.as_view(), name='fixtures'), path('teamdetails/newteam', NewTeam.as_view(), name='newteam'), path('teamdetails/<int:pk>/', PlayerDetailView.as_view(), name='teamname'), path('teamdetails/newplayers/', NewPlayer.as_view(), name='newplayer'), path('teamdetails/<int:player_details_pk>/<int:pk>/', PlayerStatistics.as_view(), name= 'playerdetails'), path('teamdetails/<int:player_details_pk>/<int:pk>/batstatistics', BatStatistics.as_view(), name= 'batstatistics'), path('teamdetails/<int:player_details_pk>/<int:pk>/bowlstatistics', BowlStatistics.as_view(), name= 'bowlstatistics'), ] In the form fields, the first two fields are the country and player name.SO whenever I select the dropdown of the country I don't want to see all the country players in the player … -
What are the best technique for having a real-time notifications, messages or other stuffs that requires an async request on django?
I just want to know if there is a best technique for achieving a async tasks like real-time notifications, messages etc. in django? Are django-channels + redis server is ok? Django celery? -
Modify a django package that's deployed to heroku
I'm getting a import error ImportError: cannot import name python_2_unicode_compatible That error comes from /app/.heroku/python/lib/python3.6/site-packages/hitcount/models.py. In my local environ i've edited that file and replaced it with code that works. How can i do the same when when the app is deployed to heroku? -
Database Inconstancy between tables using zip function - Possible Threading is required
I have a small dynamic sqlite3 DB which contains on average 100 entries with a maximum of 200 entries. See below code from my views.py: I have 7 list which is: [username], [privateip], [publicip], [bytes_Tx], [bytes_Rx], [group_policy03], [duration] So basically on average, there's 100 entries in each list. All those data needs to be matched for each line i.e. all indexes needs to be matched across all lists. To do that, I have used the zip function as per below code. for a,b,c,d,e,f,g in zip(username, privateip, publicip, bytes_Tx, bytes_Rx, group_policy03, duration03): objs = Analysis.objects.create(ana_user=a, ana_public=c, ana_private=b, ana_bytestx=d, ana_bytesrx=e, ana_policy=f, ana_duration=g) objs.save() The zip works fines because when print(a, b, c, d, e, f, g) all the data are in sync across each lists. But when it's being saved in the DB, am getting data inconsistencies between each columns whereby lets say the table should look like the below: Correct Table ana_user | ana_public| ana_private| ana_bytestx | ana_bytesrx | ana_policy | ana_duration| ------------------------------------------------------------------------------------------ testuser 1.2.3.4 10.10.10.10 6987983 287398484 policy1 23days testuser2 1.2.3.5 10.10.10.11 6987453 457398484 policy5 2days Instead am getting the below: Wrong Table ana_user | ana_public| ana_private| ana_bytestx | ana_bytesrx | ana_policy | ana_duration| ------------------------------------------------------------------------------------------ testuser 1.2.3.4 10.10.10.11 6987983 287398484 … -
Django - Show multiple images
I'm trying to show all the image correlated to a chapter. I cannot figure out what is wrong, base on what I found online it should work, but no images are display. Only the outer div is coming out on html source. By debugging the template I also notice that the for loop is taking all the chapters in the DB, not only the chapter I selected. I think I need to restrict the ChapDetail view query somehow. Can someone advise me on this two issue? model.py class Chapter(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=settings.AUTH_USER_MODEL ) book = models.ForeignKey( Book, related_name='chapters', on_delete=models.CASCADE, default='' ) title = models.CharField(max_length=130, unique=True) slug = models.SlugField(max_length=150, blank=True) created_at = models.DateField(auto_now_add=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('chap_detail') class ShowImages(models.Model): chapter =models.ForeignKey( Chapter, on_delete=models.CASCADE, default='', related_name="pics" ) picture = models.FileField(upload_to=image_dir_path, default='') def __str__(self): return self.picture.name view.py class ChapDetail(generic.ListView): model = Chapter template_name = 'chapters/chapter_detail.html' urls.py app_name = 'chapters' urlpatterns = [ path('<str:book>', views.BookChaps.as_view(), name='chap_list'), path('<str:book>/<str:slug>/', views.ChapDetail.as_view(), name='chap_detail'), # both slug fields ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' template <div style="padding-top: 10px; display: block;"> {% for i in chapter.picture_set.all %} <div> <img src="{{ i.picture.url }}" alt="Not found"> </div> {% endfor … -
How can I get the code from Server side using Instagram Basic Display API?
I am new to Instagram Basic Display API. All I need is to get the recent media published on my Instagram account. I have followed all the steps mentioned here until step 4. In step 4 when I am accessing the authorize URL it is asking me to log in to my test user instagram account first and then displaying the authorized window. Just imagine this from a user perspective. If a user is clicking on a button and if it is asking for entering the credentials of my account it seems to be like exposing my account details publicly. Once I click on the authorize button it is redirecting to my redirect_uri and I can get the code. How can I implement the same from the server-side? There will be no user interaction for the project I am working on. It should happen from the backend itself. I am using Django as the backend server. Please help me with this. -
How to create filtered field in admin?
I would like to change the basic behavior in admin while creating new class B to show me just array-field of class A and not the whole object. Can someone help me please? Thank you in advance class A: name = models.Charfield() array = ArrayField(models.CharField()) class B: array_from_A = models.ManyToManyField(A) -
How do I define my own record sampling order? Django
I want to add the ability to define and then the current record will be displayed. I am thinking of adding an additional IntegerField field that will change the order, but I don't think this is a good thing. There is also an option to make a field associated with the current model and recursively select the next one. What's your advice? -
How to make form appear under the button I clicked?
I am trying to make threaded comment system. I am using django, so this is my comment form: <form id="commentwin" name="writecomment" method="POST" action="{% url 'comment_write2' pk=post.pk %}" style="display:none"> {% csrf_token %} <p> <label for="author">Username:</label> <input type="text" name="author" required id="author"> </p> <textarea name="text" required id="text" cols="100" rows="7"></textarea> <button type="submit">Confirm</button> </form> I want to make above form appear under the parent comment, when 'reply' button in the parent comment clicked. Also, It should disappear when another reply button clicked. How can I build it? Thanks. -
How to say to Django not to hash user passwords?
My user model is django.contrib.auth.models.User. By default it uses PBKDF2 algorithm to encrypt passwords, so I see hashes of the passwords in the database. Is there a way to switch off the encryption so I could read the passwords? I know that is not a good practice generally. I have this purpose because I encrypt passwords on Frontend level and pass the hashes through REST framework. They are supposed to be used to check signatures and to do other crypto stuff, so I need the passed passwords themselves and I don't want to create a custom user model (or one-to-one model) to store hashes in a separate field somewhere. -
__str__ not showing String
I'm writing a Django application and upon login I want it to show the first and last names of the user. This is my model - class Admins(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user.is_admin = True first_name = models.CharField(max_length=256) last_name = models.CharField(max_length=256) def __str__(self): return "{} {}".format(self.first_name, self.last_name) When I call the str function in my views.py it returns - "function Admins.str at 0x00000135A3083708" Here is my view - def AdminLandingPage(request): name = Admins.__str__ print(name) #using this part to display above mentioned error return render(request,'form1/adminlanding.html',{'USTYPE':"ADMIN","FN":name}) When I checked my HTML file, it showed up blank. It was supposed to display the first and last name. Instead, neither the string (name) nor the context is able to show this. Here is my HTML file - <body> <p> {{FN}} </p> -
Send PUT Request from Tabulator to Django REST Endpoint (currently getting 403 Error)
I am using Tabulator with Django to edit a model. I am getting a 403 error when I send a PUT call to an API endpoint which works fine via Postman. My question is: how can I correctly make a call from Tabulator to do this? I am pretty new at this stuff (both Django and especially JavaScript) so apologies if I've missed something basic. The html file is a Django template. The table is populated via an Ajax call to a REST endpoint (provided using Django REST Framework). This GET request works fine and the table populates. I have another endpoint for updates which does not require authentication. This works fine using Postman or using the Python request call below to test, however I cannot get it to work from Tabulator using the table.setData command. import requests apiURL = 'http://localhost:8000/mymodel/api/cust_listapi/2/' payload = {"name":"JAMES EARL JONES"} response = requests.put(apiURL,data=payload) My tabulator code is below. The variable ajaxConfigPut is set to override the default form method used by Tabulator, and changed it to json, and also used a fetch parameter to force omit any credentials. This is then used in the table.setData call later on (table.setData(updateurl, updateData, ajaxConfigPut);). <div id="example-table"></div> <script …