Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to display all the reviews for the particular product?
With the below code i am adding reviews for some particular product in the database and it is doing good but the problem is while displaying the reviews for the selected product.I get confused how can i display the all reviews of some product and which review done by which user at what time? models.py class Product(models.Model): name = models.CharField(max_length=250) description = models.TextField(blank=True) featured = models.BooleanField(default=False) def __str__(self): return self.name class Review(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) review = models.TextField() date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.review views.py def detail(request,pk): product = College.objects.get(pk=pk) form = ReviewForm() return render(request,'products/detail.html',{'product':product,'form':form}) @login_required(login_url='products:signin') def review(request,pk): if request.method == "POST": form = ReviewForm(request.POST) if form.is_valid(): review = form.save(commit=False) review.product = Product.objects.get(pk=pk) review.user = request.user review.save() messages.success(request, "Review saved") return redirect('products:detail',pk) else: messages.error(request,'error in form') return redirect('products:detail', pk) detail.html <h3>All reviews(total.no. of reviews?)</h3> # Here i want to display all reviews and which is done by which user and at what time <div class="col-lg-6 col-md-6 mb-6"> <form method="post" action="{% url 'products:review' product.pk %}"> {% csrf_token %} {% form.as_p %} <input type="submit" class="btn btn-success"> </form> </div> -
Why in response the data of different table coming in different array?(using Django, Rest framework, MySql)
Actually I have joined various tables in Django using Rest framework and MySql database. The response is coming correctly but data from different table is coming in different arrays. But I want the response in a single array.I am posting the present response and the required response. Please help me out with this. The response is coming like this : { "count": 282566, "next": "http://127.0.0.1:8000/inventoryregister/?limit=1000&offset=1000", "previous": null, "results": [ { "inventory_batch": { "inventory_reg": { "id": 1, "company_id": "28", "inventory_group_id": "1", "is_owned": "1", "cost_center": { "location": "Bangalore Production", "lob_id": 230, "nick_name": "Bangalore Production", "lob": { "lob_name": "LAB", "cs_id": "3" }, "department": null }, "inventory_date": "2019-04-19", "inventory_action": "2", "product_type2_id": "57", "asset_type": { "asset_type": "Fixed Assets" }, "dimension": null }, "batch_no": "New10190420192" }, "barcode_no": "0803843276" } But I want the response in this way : { "count": 282566, "next": "http://127.0.0.1:8000/inventoryregister/?limit=1000&offset=1000", "previous": null, "results": [ { "id": 1, "company_id": "28", "inventory_group_id": "1", "is_owned": "1", "location": "Bangalore Production", "lob_id": 230, "nick_name": "Bangalore Production", "lob_name": "LAB", "cs_id": "3" "department": null "inventory_date": "2019-04-19", "inventory_action": "2", "product_type2_id": "57", "asset_type": "Fixed Assets" "dimension": null "batch_no": "New10190420192" "barcode_no": "0803843276" } } -
What is the cost of many null-foreign keys in a model?
I have a Post model, an Image model, and a Channel model. I have a foreign key in the Image model connected to the Post model. Additionally, I am trying to add a nullable foreign key connected to the Channel model. class Image(models.Model): post = models.ForeignKey(Post, null=True, blank=True, on_delete=models.CASCADE) comment = models.ForeignKey(Comment, null=True, blank=True, on_delete=models.CASCADE) news = models.ForeignKey(news_models.News, null=True, blank=True, on_delete=models.CASCADE) message = models.ForeignKey(messenger_models.Message, null=True, blank=True, on_delete=models.CASCADE) channel = models.ForeignKey(messenger_models.Message, null=True, blank=True, on_delete=models.CASCADE) file = ProcessedImageField(upload_to='uploads/%Y/%m/%d/', processors=[Transpose()], format='JPEG', options={'quality': 50}, blank=True) My concern is that the channel field will be mostly null as I only need one image per channel. But the image has to be connected with a Post. So each one channel has one image that is connected to the post. However, There will be incompariably more posts and images than a channel, so the channel field in the Image model will be wasted most of the time. Another solution I thought of is creating a new image model exclusively for the Channel model and when the new image instance is created, manually copy the image from the original image-post connected instance. But I cannot relationally connect my Channel model to the Image model in this way, which … -
Images on my Django website are not loading
I am having images on my menu template which when clicked I want to redirect to another template in Django **Below is my code for the menu template:** {%for count in item%} <div class="col-md-6 col-lg-4 menu-wrap"> <div class="heading-menu text-center ftco-animate"> <h3>{{count.supper}}</h3> </div> <div class="menus d-flex ftco-animate"> <div class="menu-img img" style="background-image: url({{count.pic.url}});"></div> <div class="text"> <div class="d-flex"> <div class="one-half"> <h3>{{count.name}}</h3> </div> <div class="one-forth"> <span class="price">${{count.price}}</span> </div> How can i make this happen ? Can an onclick event be applied? -
how to scroll to bottom after ajax insert using jquery or js?
how to create array using for loop in django view?? success: function(result) { console.log("result : " , result); alert("insert success") window.history.pushState("", "", '/wm/myshortcut/') var raw_template = $('.myshortcut_row').html(); var tpl = _.template(raw_template); var rendered = tpl({ shortcut_id : result.shortcut_id, shortcut_title : result.shortcut_title, shortcut_content : result.shortcut_content, }); $(rendered).appendTo($('.myshort_list_area')); // I want to scroll to bottom how to make it? } Can I make the bottom visible through the scroll after input? Another question. I want to move the scroll up a little after moving as below. Is it possible? $ (". go_btn"). click (function () { const number = $ (". go_input"). val (); if (number == 1) { $ ('html, body'). animate ({ 'scrollTop': $ ("# index_first"). offset (). bottom }); } $ ('html, body'). animate ({ 'scrollTop': $ ("# index _" + number) .offset (). top }); }} The reason is that some of them are covered because of the navigation. Thank you very much for letting me know about this. -
Multiple word search page in django
Basically, I need to create a search page in django which has input fields say rollno, name, class, teacher's name . A user might enter any or all of the details and click search. It should go to another html template and view the details of the students matching it to the details entered. I have an html page search.html and results.html. search.html <input type="text" name="roll_no" class="form-control" placeholder="roll no" > <input type="text" name="name" class="form-control" placeholder="name" > <input type="text" name="class" class="form-control" placeholder="class" > <input type="text" name="teacher_name" class="form-control" placeholder="teacher's name" > results.html It should show only the details of the students that matches with the input text entered in the search.html and not all Roll_no:<span class="float-right">{{post.roll_no}} Name:<span class="float-right">{{post.name}} Class:<span class="float-right">{{post.class}} Teacher's_name:<span class="float-right">{{post.t_name}} Father's_name:<span class="float-right">{{post.fa_name}} Please do help, the videos and tutorials I have looked so far show searching which search for say posts and show them in the same page itself. -
Delete the particular user without using admin panel in django
I have created my models using django user model. I am able to perform the edit functionality to the created form.Now i want to do DELETE the particular user details by using DELETE button.Here is my code forms.py class EditProfileForm(forms.ModelForm): class Meta(): model = User fields = ['first_name','last_name','username','email','password'] help_texts={ 'username': None } views.py def delete_profile(request, id): profile = UserProfileInfo.objects.get(id=id) if request.method == 'POST': profile.delete() return HttpResponseRedirect(reverse('signupapp:index')) return render(request, "signupapp/delete_profile.html", {'profile': profile}) delete_profile.html <form action="" method ="POST"> {% csrf_token %} <p>Are you sure to delete "{{UserProfileInfo.username}}"?</p> <input type="submit" value="Delete"/> </form> Delete button link index.html <a href="{% url 'signupapp:delete' request.user.id %}"><input type="button" value="Delete"/></a><br> When i run this code it is showing an error like this DoesNotExist at /delete/9/ UserProfileInfo matching query does not exist. Can anyone help me to clear it. Thanks in advance.. -
Is there a get_model equivalent for serializers?
I've read the docs on serializers and Googled (a lot), but haven't found the exact answer I'm looking for. I'm trying to write a generic "archive" process (class) to handle changing a status field to "archived" for any model instance based on what's passed in the URL. For example: example.com/archive/clients.client/123 That would change the status to "archived" for ID 123 of the Client model. Here's my URLconf: path('archive/<model>/<int:pk>/', Archive.as_view()), And here's my view class. I had first got this working for a specific model, so I've copied that code and am trying to adapt it to be more generic. Also, I know this needs more bulletproofing, but I'm trying to show the simplest version of my code. class Archive(RetrieveAPIView): def retrieve(self, request, model=None, pk=None, *args, **kwargs): app, model_name = model.split('.') get_model = apps.get_model model = get_model(app, model_name) self.queryset = model.objects.all() instance = self.get_object(pk=pk) if instance.status == 'archived': return APIMessage('That item has already been archived.', message_code='already_archived') setattr(instance, 'status', 'archived') instance.save() serializer = self.get_serializer(instance) return Response(serializer.data) When I try to run this as is, I get: 'Archive' should either include a `serializer_class` attribute, or override the `get_serializer_class()` method. And that was pretty much what I expected, but I don't have anything I … -
How can i grouping django table
I have an app named Post and my models.py for the app have more than 10 tables/class. Under my admin.py My question is; how can i gruoping these tables I want like this for example; posts -Gönderiler -Kategori listesi -Tag listesi Games -Game maps -Matchs -Oyuncu Games1 -League of legends game... -
Django Login will Authenticate but redirect fails only on remote server
I have just finished building my web app and migrated it to a digital ocean droplet. The problem that I am having is I can run runserver 0.0.0.0:8000 and use my server ip to get to my homepage, landing-page, signup etc. As well I am able enter incorrect credentials and be redirected back to sign-in again. As soon as the correct credentials are entered Django hangs up until I stop the server. On my local machine I do not have this problem, as well by connecting through LAN I am able to login successfully. My local machine connects to a database on a droplet in the same datacenter as my Django prod server. Strangely, According to my database the attempt to login is successful. The issue seems to be something related to redirecting to my view. by changing the redirect to my landing page and adding print statements to my view I can see that it is never accessed following authentication. Mysql version is identical across both instances. From my Django Instance: I can login to the database from my instance I can create a new SuperUser from my instance manage.py shell I can fill out the signup form and … -
Django Basic Auth
I have two serializers... MyRegisterSerializer inherits and extends a popular app/package, django-rest-auth, which connects to a fairly standard user table. I also have a Model and serializer for a custom app, TeamSerializer (a one-to-many relationship with users). When a user signs up, I would like them to be able to join a team at the same time, so I somehow need to create a team, return the team ID and then pass that ID to the RegisterSerializer, so that the ID of the team can be stored in the User table. I know I could make two calls, first to create the team and return the value, and then pass it to the register serializer, but is there a way to do this all in one serializer? I am a n00b at python, and cant find a great example of this, considering I have to return the get_cleaned_data() function as it is. Thank you! class TeamSerializer(serializers.ModelSerializer): class Meta: model = Team fields = ('id', 'name', 'logo', 'user') class MyRegisterSerializer(RegisterSerializer): first_name = serializers.CharField() last_name = serializers.CharField() def get_cleaned_data(self): super(MyRegisterSerializer, self).get_cleaned_data() return { 'team_id': <How do I get this value> 'username': self.validated_data.get('username', ''), 'position': self.validated_data.get('password1', ''), 'email': self.validated_data.get('email', ''), 'first_name': self.validated_data.get('first_name', ''), … -
How to add static file in django before pushing
I'm coding css and javascript file for my web project. That files I put in app folder. I use "git add ." and "git push origin +(branch_name)", but I clone project again, I don't call that static files I wrote. How do I solve problem? -
How to make a loop in views.py in django
I don't want to repeat Destination function again and again in separate variables. I tried to make different variables and equaled them to Destination() but it didn't work. How to make a loop in it so that I don't have to repeat it? def index(request): dest1 = Destination() dest1.desc = 'Hello, How are you?' dest1.img = '01.jpg' dest2 = Destination() dest2.desc = 'Hello, HOw are you?' dest2.img = '02.jpg' context = { 'dests1': dests1, 'dests2': dests2, 'dests3': dests3 } return render(request, 'index.html',context) -
Importing a .xlsx file into models, receiving an Integer out of range error for the DateField: Line number: 1 - integer out of range
I am attempting to import a spreadsheet of video games into my django database. I have set up the models with date fields, and I believe I have formatted my spreadsheet so that it matches with what Django is expecting. I am using the django import-export package. I have tried to manually set the formatting in the django settings.py file, but that doesn't seem to fix it. models.py releaseDateJP = models.DateField(null=True,blank=True) releaseDatePAL = models.DateField(null=True,blank=True) releaseDateNA = models.DateField(null=True,blank=True) settings.py DATE_INPUT_FORMATS = ['%Y-%m-%d'] Here is what the first line of my spreadsheet looks like: I expect for my models to be filled with the appropriate data; the release dates. But the first date field (releaseDateJP), is what I believe to be causing the error:Line number: 1 - integer out of range -
Django count all child models from parent in one query
I'm trying to count all children from my parent model but I cannot make It work. See below for my model and things that I have tried. Model class ParentXX(models.Model): created = models.DateTimeField(auto_now_add=True, null=True) last_updated = models.DateTimeField(auto_now=True) name = models.CharField(max_length=200,null=False,blank=False,unique=True) class ChildrenXX(models.Model): created = models.DateTimeField(auto_now_add=True, null=True) last_updated = models.DateTimeField(auto_now=True) name = models.CharField(max_length=200,null=False,blank=False,unique=True) parent_sample = models.ForeignKey(ParentXX, models.CASCADE, blank=False, null=False, related_name='child_sample') Code cnt = ParentXX.objects.filter(name="xx").annotate(c_count=Count('child_sample')) #Not working cnt = ParentXX.objects.filter(name="xx").annotate(c_count=Count('parent_sample')) #Not working print(c_count) -
Uninstalling django-tinymce. Import error when makemigrations
Thanks for taking the time to read this. I was not happy with TinyMCE extension in django and decided to switch to django-summernote. I first ran pip uninstall django-tinymce Removed all mentions of tinymce in the actual project. Followed the instruction to install django-summernote. Upon completion I decided to run python manage.py makemigrations python manage.py migrate to apply new extension, but get an error: File "/Users/rasulkireev/Sites/dj-pw/now/migrations/0006_auto_20190703_0134.py", line 4, in <module> import tinymce.models ModuleNotFoundError: No module named 'tinymce' I'm not sure why would Django care about what I did previously since I am simply asking to replace the editor. I can't run python manage.py runserver either. I can't do anything before fixing this. I beg you guys, please help. Note: I would ideally want to keep the contents of my current database. Thanks for taking the time to read this. -
How to link AbstractUser to Group and query in Views for Business Logic
I have limited the amount of files a user can upload to my site using a logical query in my upload app's views.py file. Long story short, after the user has uploaded 5 files, they are redirected to a page that says they must become a premium member. I am now trying to add to that logic by checking if they are in the "Free User" group. If they are not, they should be allowed to upload an unlimited number of files. So far I have used the admin panel to create two groups. One is "Free User" and one is "Gold User". I gave both groups add, change, delete, view permissions for my "beatupload" app. I added this code to my users models.py # users/models.py from django.contrib.auth.models import AbstractUser, Group from django.db import models class CustomUser(AbstractUser): pass # add additional fields in here group = models.ForeignKey(Group, on_delete=models.CASCADE, default=1) def __str__(self): return self.email I see that I have a field in my users_customuser table for group_id, but when I change the group in the admin interface no changes reflect. When I check the table using select * from auth_group I see that I have id and group name, being Free … -
How to copy image to a new variable
I'm trying this code, but I'm doing something wrong. class Photo(TimestampedModel): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) image = models.ImageField(upload_to="photos") image_card = models.ImageField(upload_to="photos", null=True) def save(self, *args, **kwargs): if not self.id: self.image = self.compressImage(self.image) self.image_card = self.resizeImage(self.image) super(Photo, self).save(*args, **kwargs) The idea is to create a second image (image_card), with a new size. In the end, I get an image for image_card but not for image. The methods compressImage() and resizeImage() works correctly, but I suspect that resizeImage is getting the same image instance. If I comment the line self.image_card = self.resizeImage(self.image) , image works again. -
How to use models variable as url?
In my models.py file i made a variable called hero_name. For instance, if the hero name is Bart, I want the url to be ./heroes/Bart urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('<str:hero_name>/', views.heropage, name='heropage'), ] views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse from .models import Heroes def index(request): return render(request, 'heroes/index.html') def heropage(request, hero_name): get_object_or_404(Heroes, pk=hero_name) return render(request, 'heroes/heropage.html') models.py from django.db import models class Heroes(models.Model): hero_name = models.CharField(max_length=200) -
How to fix "Error Removing corrupted schedule file 'celerybeat-schedule': error('Bad magic number',)r"
I can run the celery beat normally using the command in the terminal, but when I go to run in aws, I get the following error: [2019-07-10 11:30:35,166: ERROR/MainProcess] Removing corrupted schedule file 'celerybeat-schedule': error('Bad magic number',) Traceback (most recent call last): File "/opt/python/run/venv/local/lib/python3.6/site-packages/kombu/utils/objects.py", line 42, in __get__ return obj.__dict__[self.__name__] KeyError: 'scheduler' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/opt/python/run/venv/local/lib/python3.6/site-packages/celery/beat.py", line 476, in setup_schedule self._store = self._open_schedule() File "/opt/python/run/venv/local/lib/python3.6/site-packages/celery/beat.py", line 466, in _open_schedule return self.persistence.open(self.schedule_filename, writeback=True) File "/usr/lib64/python3.6/shelve.py", line 243, in open return DbfilenameShelf(filename, flag, protocol, writeback) File "/usr/lib64/python3.6/shelve.py", line 227, in __init__ Shelf.__init__(self, dbm.open(filename, flag), protocol, writeback) File "/usr/lib64/python3.6/dbm/__init__.py", line 94, in open return mod.open(file, flag, mode) _gdbm.error: Bad magic number Could someone please help me to understand whats's wrong? -
How to decode utf-8 encoded string in python 3?
I have the following situation: encoded_string = str('дис'.encode('utf-8')) I need to convert this to string because django's set_cookie() takes a string and I can't seem to be able to write the function f for which: f(encoded_string) == 'дис' is again. If I don't convert this string then django returns Internal server error. Can you please help? -
Serializers crash when return an instance
I am trying to add a new variable in my endpoint. Before I used cliente, but now I want to add user (for finding the cliente). The problem is that user is not in my Pedido model, so I add using user = serializers.IntegerField(). I can use it in the method without a problem, but when return the instance pedido, something is wrong. serializers.py class PedidoWriterSerializer(serializers.ModelSerializer): user = serializers.SerializerMethodField() lineas = DetallePedidoSimpleSerializer(many=True, required=False) class Meta: model = Pedido exclude = ('monto','entrega_realizada','pedido_confirmado', 'cliente',) extra_kwargs = { 'user': {'write_only': True} } def create(self, validated_data): if 'lineas' in validated_data: lineas = validated_data.pop('lineas') if 'entrega_solicitada' in validated_data: entregas_solicitadas = validated_data.pop('entrega_solicitada') user = self._kwargs.get('data').get('user') bandera = True c = Cliente.objects.get(usuario_id=user) validated_data['cliente'] = c if (not c.habilitado): bandera = False if bandera: total = 0 for l in lineas: print(2) print(l) p = Producto.objects.get(pk=l['producto'].id) if ((not p.activo) or (not p.stock) or (not(l['cantidad']>0 and l['cantidad'] <1000))): bandera = False else: today = datetime.now() prom = p.ofertas.filter(activa=True, desde__lte=today, hasta__gte=today).last() if prom: monto_descuento = (p.precio * prom.descuento) / 100 total = (p.precio - monto_descuento) * l['cantidad']\ + \ total else: total = p.precio * l['cantidad'] + total if total < c.ciudad.monto_minimo: bandera = False if bandera: for e in … -
How to add linkable text in django 2.2 blog post from admin panel
class BlogPost(models.Model): # blogpost_set -> queryset # id = models.IntegerField() # pk user = models.ForeignKey(User, default=1, null=True, on_delete=models.SET_NULL) image = models.ImageField(upload_to='image/', blank=True, null=True) title = models.CharField(max_length=120) slug = models.SlugField(unique=True) # hello world -> hello-world content = models.TextField(null=True, blank=True) publish_date = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) objects = BlogPostManager() class Meta: ordering = ['-publish_date', '-updated', '-timestamp'] def get_absolute_url(self): return f"/blog/{self.slug}" def get_edit_url(self): return f"{self.get_absolute_url()}/edit" def get_delete_url(self): return f"{self.get_absolute_url()}/delete" def show_url(self, obj): return format_html("<a href='http://pre.com{0}'>{0}</a>", obj.url) -
Why is my queryset only returning particular properties of my model instance in 'get' request?
Using django 1.11, I have a model with particular properties that I want to return with a get request(in my case get_queryset is returning a response to the get request), and it's only returning particular properties of a given model instance(a.k.a. object, a.k.a. record). I want all the properties of the record, not just the ones django decides by default to give me using a queryset. I've tried using the 'ekg.objects.all().filter(user=request.user).values('user', 'id') to try to get particular values returned from the database to no avail. class Ekg(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank = False, null=False) ekgId = models.AutoField(primary_key=True) sampling_rate = models.DecimalField(max_digits=5, decimal_places=2, null = False, blank = False) dataTag2 = models.TextField(null = False, blank= False) dataTag3 = models.TextField(null = False, blank= False) timestamp = models.DateTimeField(auto_now_add=True, null=False, blank=False) #date and time of the signal added to db ''' ''' class EkgAPIView(mixins.CreateModelMixin, generics.ListAPIView): permission_classes= [permissions.IsAuthenticated] authentication_classes= [JSONWebTokenAuthentication] serializer_class = EkgSerializer def get_queryset(self): #return all qs = Ekg.objects.all().filter(user=request.user).filter(ekgId=2).values('user', 'ekgId', 'sampling_rate', 'dataTag2', 'dataTag3', 'timestamp') return qs output using api endpoint(not desired) [{"sampling_rate":"212.00","dataTag2":"anotherDatatag2","dataTag3":"anotherDatatag3"}] expected (timestamp not exactly that format, but sending me back something [{"ekgId ":"2", "timestamp":"July 10, 2019 - 22:19:47","sampling_rate":"212.00","dataTag2":"anotherDatatag2","dataTag3":"anotherDatatag3"}] -
Math expression in html format
My study shows the only effective method to include the mathematical expression on my html pages is mathType. It converts the math expression to html code. That is not supported in some of the browsers (including chrome) however. Is there any alternative?