Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django image upload in different template
How can I display uploaded images in a different template from the form> in Django. I don't get it how to render it to another page. I the upload template has the form to upload image. And I want to display those images in profile but I am not able to do so . It is only working ienter image descript -
How to pass a Django Object to Javascript File (template buyed in envato elements)
dears!! I'm trying to get a Django object in a Javascript file. My objective is to to connect a Django template to a Javascript file and render my model info in the website. My models.py: class Event(models.Model): _id = models.ObjectIdField(blank=True, null=False) title = models.CharField(max_length=200) slug = models.SlugField(max_length=100) description = models.TextField(blank=True, null=True) event_date = models.DateTimeField(null=True, verbose_name="Date") event_creation = models.DateTimeField(verbose_name="Creation", auto_now_add=True) start = models.DateTimeField(null=True, verbose_name="Start") end = models.DateTimeField(null=True, verbose_name="End") event_updated = models.DateTimeField(verbose_name = 'Updated',auto_now=True) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f'event_{self.title}' class Meta: db_table = 'event' My serializers.py: class EventSerializer(serializers.ModelSerializer): # _id = serializers.ReadOnlyField() channels = Event class Meta: model = Event fields = '__all__' My views.py: class Calendar(LoginRequiredMixin,TemplateView): template_name = "calendar.html" queryset = Event.objects.all() serializer = EventSerializer(queryset, many=True) data = JSONRenderer().render(serializer.data) def get(self, request): context = {'event': self.data} return render(request, 'calendar.html', context) #FOR THE FUTURE: I WANT TO USE POST METHOD # def post(self, request, *args, **kwargs): # serializer = self.get_serializer(data=request.data) # serializer.is_valid(raise_exception=True) # event = serializer.save() # return Response({ # "event": EventSerializer(event, context=self.get_serializer_context()).data, # "token": AuthToken.objects.create(event)[1] # }) the Javascript file (I've detected that the object that render events on calendar are the one in commented lines. What I want is to pass my Django Object into that list, … -
How Can I get a Particular User Group Name in Django Form Query
I have a Django form with a Drop Down from User Groups which is Created from Django Admin Panel. I have 3 groups with various permissions so in this form I want to get only the Group named 'Guest' from the drop down and disabled. What is the best way of doing it. Below is what I have tried but I am getting the following errors: ImportError: cannot import name 'getgroups' from 'os' class GuestUserForm(UserCreationForm): email = forms.EmailField group = forms.ModelChoiceField(queryset=Group.objects.get('Guest'), required=True) class Meta: model = User fields = ['username', 'email', 'password1', 'password2', 'group'] -
Django can not import site module
I am trying to run a simple Hello World app with Django but for some reason, it does not import myapp from mysite. -
Serve static files from Cloudflare's R2
Architecture Description I have a Django app hosted on an Azure App Service container and proxy through Cloudflare's DNS. The app works great, and using WhiteNoise I am able to serve static files stored in the Azure App Service storage container that is provided with the App Service (10 GB). Thing is, the storage serves files used by the Web App only (files uploaded during build, there's no option to manually add other files), and it is limited to 100GB/month of egress bandwidth. I would like to try and use [Cloudflare's R2] storage, as it has unlimited bandwidth, and allows you to upload any kind of files. I'll mainly be using images. Question How can static files be serve from Cloudflare's R2 on a Django app? -
Reverse Lookup for Inherited Models in Django
I have several Django model definitions. There is a parent class contains a foreign key to another class, and there are multiple model classes that inherit from the parent. class Foo(models.Model): pass class Parent(models.Model): foreign_key = models.ForeignKey(Foo, on_delete=models.CASCADE) class Child1(Parent): pass class Child2(Parent): pass Given an object of type Foo, I am trying to perform a reverse lookup to find all objects that are either of type Parent or subclass Parent and that link to that specific object. However, if I use foo.parent_set I would only get the objects of the Parent class that are related to foo, while if I try doing so with any of the child classes it errors out because those don't directly specify a relationship with the class Foo. Is there any way to get a list of all objects that are of type Parent or inherit from Parent that contain a foreign key to an object of type Foo? -
Django query with conflicting fields returns duplicate answers
Query: cameraSystems = DWCloudSystem.objects.filter(isShared=False).filter(company_key=comp) cameraSystems = cameraSystems | DWCloudSystem.objects.filter(isShared=True).filter(location__owners=comp) DWCloudSystem is a model with that contains: "company_key" a foreign key representing a Company model object, "location" a foreign key representing a place object, "isShared" a Boolean field A place object also contains a "owners" ManyToMany field for company objects. Essentially the goal is to have a DWCloudSystem which is owned by a company which is at a place to be returned if isSharing is false or ifSharing is true then any company that belongs to the place object will be able to access that DWCloudSystem along with its "owner" company which is represented by the company_key field (which may or may not be a member of the "owners" field that is apart of the place model) The issue is this query is returning the same company twice even though isShared is set to True and thus the other query should be empty. Both work correctly if not combined. -
Django REST Framework, implicatoins of [] in search
I have a very basic Django API which makes a query in elasticsearch. The output shows the query_parameters and the search.query. Why I cannot pass the country variable in this case 'DE' to the search.query as shown in the output? Could you please explain the implications of [] in country[]? class ESNumView(APIView): """Obtain number of articles after a search in titles and abstract in ES""" def get(self, request, *args, **kwargs): query = self.request.query_params.get('query') country = self.request.query_params.get('country') print(self.request.query_params) search = Search(index=constants.ES_INDEX) q = Q('bool', must=[ Q('multi_match', query=query, fields=['title', 'abstract']), Q('terms', country=country) ] ) s = search.query(q) pprint(s.to_dict()) num_count = s.count() return Response(data=[{'search_count': num_count}]) The output is; <QueryDict: {'query': ['membrane'], 'country[]': ['DE']}> {'query': {'bool': {'must': [{'multi_match': {'fields': ['title', 'abstract'], 'query': 'membrane'}}, {'terms': {'country': None}}]}}} -
why does the sqlite3 keeps telling me that i don't have a table called User?
i create a model on django this way: class User(models.Model): username = models.CharField(max_length=50) email = models.CharField(max_length=50) password = models.CharField(max_length=50) phone = models.CharField(max_length=80) and i then i use both commands: python manage.py makemigrations python manage.py migrate and still i get the error: django.db.utils.OperationalError: no such table: myapp_User (im using sqlite3 as a default database) is there a way to solve it or should i use PostgreSQL better? -
TypeError NoneType in Python script when running Django application
I get the error: TypeError: 'NoneType' object is not subscriptable. You can view the code below. The strange thing is when I run the code in Notebook it works. But when I run this in Django I get this NoneType error in return. I need this code in my Django application, so can someone please help. def update_pie(year, changed_id): dff = data[data['year'] == year] if changed_id[-1] == "." or changed_id[-1] == "1": dff = dff.groupby('air quality', as_index=False).count() dff = dff.rename(columns = {"country": "count"}) elif changed_id[-1] != "1" and changed_id[-1] != ".": dff = dff[dff['continent code'] == int(changed_id[-1]) - 1] dff = dff.groupby('air quality', as_index=False).count() dff = dff.rename(columns = {"country": "count"}) -
Host match not found. Google firebase messaging
I am buliding uber-like-delivery app using django. I just implemented the firebase messaging but each time i try to add a phone number so that it sends a verification code it give me the error "Hostmatch not foundenter image description here" so please anyone with an idea on how i can solve this. I tried the whitelisting thing , itdoesnt change anything or maybe its my code. ` Phone Number <div id="recaptcha-container"></div> <div id="get-code" class="input-group mb-3 {% if request.user.customer.phone_number %} d-none {% endif %}"> <label> <input type="text" class="form-control" placeholder="Your phone number"> </label> <div class="input-group-append"> <button class="btn btn-warning" type="button">Send code</button> </div> </div> <div id="verify-code" class="input-group mb-3 d-none"> <label> <input type="text" class="form-control" placeholder="Verification code"> </label> <div class="input-group-append"> <button class="btn btn-success" type="button">Verify code</button> </div> </div> <div id="change-phone" class="input-group mb-3 {% if not request.user.customer.phone_number %} d-none {% endif %}"> <label> <input type="text" class="form-control" disabled value="{{ requeat.user.customer.phone_number }}"> </label> <div class="input-group-append"> <button class="btn btn-warning" type="button">Change</button> </div> </div> </div> function onVerify(idToken) { var form = document.createElement("form"); form.method = "POST"; var element1 = document.createElement("input"); element1.name = "id_token"; element1.value = idToken; form.appendChild(element1); var element2 = document.createElement("input"); element2.name = "action"; element2.value = "update_phone"; form.appendChild(element2); var element3 = document.createElement("input"); element3.name = "csrfmiddlewaretoken"; element3.value = "{{ csrf_token }}"; form.appendChild(element3); document.body.appendChild(form); form.submit(); … -
Use data from get_context_data in form_valid method
How can i use value from dictionary context in form_valid? eg. def get_context_data(self, **kwargs): context_data = super(ProductView, self).get_context_data(**kwargs) product_obj = Product.objects.get(id=self.kwargs['pk']) user_id = product_obj.user_id user_obj = User.objects.get(id=user_id) context_data['email'] = user_obj.email return context_data def form_valid(self, form, **kwargs): email = context_data['email'] # need use this value return super(ProductView, self).form_valid(form) -
How to handle API generated reset password routes in Next.js
I'm using Djnago with Djoser as my backend, and Next.js as my frontend. When a user requests to reset their password, they receive an email with a recovery link following this pattern http://localhost:3000/password-reset/{uid}/{token}. I was able to handle the password recovery flow successfully using [...params] catch all dynamic route in Next.js. However, a user can go to http://localhost:3000/password-reset/abc/def and still be able to view the reset password page, even though they obviously won't be able to change any password. Is there a way to verify if the route has been generated by the backend and set the page permission based on that? Any help would be appreciated. Thank you -
Error rendering page: Error: Failed to load script: /_next/static/chunks/pages/_error-2280fa386d040b66.js
This website runs properly locally but then when I deployed it to heroku, it would load halfway and then go blank, the chrome console pops up errors I haven't still been able to find solutions to (It was built using next.js, django and postgresql). I'm new to all of this, please I need help? favourndubuisi.herokuapp.com -
Django Debug Toolbar BaseConnectionHandler.all() error
I am using docker and the debug toolbar gives the following error: BaseConnectionHandler.all() got an unexpected keyword argument 'initialized_only' I wrote the following code in the settings.py file : if DEBUG: MIDDLEWARE += [ 'debug_toolbar.middleware.DebugToolbarMiddleware', ] INSTALLED_APPS += [ 'debug_toolbar', ] import os import socket hostname, _, ips = socket.gethostbyname_ex(socket.gethostname()) INTERNAL_IPS = [ip[: ip.rfind(".")] + ".1" for ip in ips] + ["127.0.0.1", "10.0.2.2"] I wrote the following code in the urls.py file : if settings.DEBUG: import debug_toolbar urlpatterns += [ path('__debug__/', include(debug_toolbar.urls)), ] -
Django: Updating Old Migration Files that Have `django_mysql.models.JSONField`?
In older versions of Django, you could use JSON fields in models via django_mysql.models.JSONField. In new versions of Django, JSONField is no longer in django_mysql.models. I've updated my models.py files accordingly, but I still have old migrations files that look like this: # Generated by Django 2.1.7 on 2019-07-17 22:59 from django.db import migrations import django_mysql.models class Migration(migrations.Migration): dependencies = [ ('rss', '0009_delete_patternmatchingkeywords'), ] operations = [ migrations.AddField( model_name='rssoutput', name='industries', field=django_mysql.models.JSONField(default=list), ##<== ERROR ), ] Now when I run makeMigration, I get this error: AttributeError: module 'django_mysql.models' has no attribute 'JSONField' What is the correct procedure to address this? I'm using: Django 4.0 Python 3.9.13 django-mysql 4.7.0 -
forms.Select(attrs={'class': 'form-control' Edit form and get numbers 1-5 in dropdown
Am wondering how i can get this html code into a forms.py in my ReviewForm as widgets. This code: 'rating': forms.Select(attrs={'class': 'form-control',}), Should be as the html code under with 1-5. And also be saved in models so the rating still gets saved when edited. So basicly allow the forms.py when you edit it to render a dropdown with 1-5 atm its just a dropdown with no numbers cant figure out how to get numbers in the dropdown with the widget. <div> <label>Rating</label><br> <select class="form-control" name="rating"> <option value="1">1</option> <option value="2">2</option> <option value="3" selected>3</option> <option value="4">4</option> <option value="5">5</option> </select> </div> forms.py class ReviewForm(forms.ModelForm): class Meta: model = Review fields = ('content', 'rating') widgets = { 'content': forms.Textarea(attrs={'class': 'form-control'}), 'rating': forms.Select(attrs={'class': 'form-control',}), } Models.py class Product(models.Model): category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.SET_NULL) sku = models.CharField(max_length=254, null=True, blank=True) name = models.CharField(max_length=254) description = models.TextField() has_sizes = models.BooleanField(default=False, null=True, blank=True) price = models.DecimalField(max_digits=6, decimal_places=2) rating = models.DecimalField(max_digits=6, decimal_places=2, null=True, blank=True) image_url = models.URLField(max_length=1024, null=True, blank=True) image = models.ImageField(null=True, blank=True) def __str__(self): return self.name def get_rating(self): reviews_total = 0 for review in self.reviews.all(): reviews_total += review.rating if reviews_total > 0: return reviews_total / self.reviews.count() return 0 class Review(models.Model): product = models.ForeignKey(Product, related_name='reviews', on_delete=models.CASCADE) rating = … -
ValueError: Field 'id' expected a number but got 'shafquetnaghmi'
models.py After adding this model,when i run python manage.py migrate this problem arises,there i added default='shafquetnaghmi' in sender but i removed it ,still it is not working. class instantmessage(models.Model): sender=models.ForeignKey(User,related_name='sender', on_delete=models.CASCADE,blank=True,null=True) receiver=models.ManyToManyField(User,related_name='receiver') message=models.TextField(blank=True) def __str__(self): return f'{self.message}' Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, social_django, socialapp Running migrations: Applying socialapp.0006_remove_instantmessage_sender_instantmessage_sender...Traceback (most recent call last): File "C:\Users\SHAFQUET NAGHMI\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\__init__.py", line 1822, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: 'shafquetnaghmi' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\SHAFQUET NAGHMI\socialnetwork\manage.py", line 22, in <module> main() File "C:\Users\SHAFQUET NAGHMI\socialnetwork\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\SHAFQUET NAGHMI\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 425, in execute_from_command_line utility.execute() File "C:\Users\SHAFQUET NAGHMI\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 419, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\SHAFQUET NAGHMI\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 373, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\SHAFQUET NAGHMI\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 417, in execute output = self.handle(*args, **options) File "C:\Users\SHAFQUET NAGHMI\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 90, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\SHAFQUET NAGHMI\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\migrate.py", line 253, in hanp_save return self.get_db_prep_value(value, connection=connection, prepared=False) File "C:\Users\SHAFQUET NAGHMI\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\__init__.py", line 2461, in get_db_prep_value value = self.get_prep_value(value) File "C:\Users\SHAFQUET NAGHMI\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\__init__.py", line 1824, in get_prep_value raise e.__class__(ValueError: Field 'id' expected a number but got 'shafquetnaghmi'. -
Not getting any data from request object using request.POST.get
I have a post view that receives an email and payment_method_id. However, when I send this data to this end_point I noticed that I am not retrieving any of the data from my request object. This is an example of what I am sending: {"email":"test@gmail.com","paymentMethod_id":"pm_1LFMSIDMftTw233Mz3S9xkqE"} This is my view @csrf_exempt @api_view(['POST']) def save_stripe_info(request): email = request.POST.get("email") payment_method_id = request.POST.get('payment_method_id') print('email is', email) print('payment method', payment_method_id) customer = stripe.Customer.create( email=email, payment_method=payment_method_id ) return Response(status=status.HTTP_200_OK, data={ 'message': 'Success', 'data': {'customer_id': customer.id} }) -
How to edit/change a field in a model without using a form in django
So im creating a Multiple choice quiz and I want to be able to add different quizzes with different difficulty and have around 20 questions for each quiz that i make. From those 20 questions the program should randomly select 10 questions and displays them SEPERATELY. So basically I got the questions to display seperately and created a few models but i also want to save the users results after they have answered the 10 questions to the database and how many times they attempted the same quiz. Is there a way to do this without using a form? models.py from django.db import models from django.contrib.auth.models import User class Quizzes(models.Model): CHOICES = ( ('Easy', 'Easy'), ('Medium', 'Medium'), ('Hard', 'Hard'), ) name = models.CharField(max_length=200) quizDesc = models.TextField() difficulty = models.CharField(max_length=200, null=True, choices=CHOICES) class Meta: verbose_name_plural = "Quizzes" def __str__(self): return self.name class QuestionList(models.Model): quiz = models.ForeignKey(Quizzes, on_delete=models.CASCADE) questNum = models.IntegerField(null=True) question = models.CharField(max_length=200,null=True) op1 = models.CharField(max_length=200,null=True) op2 = models.CharField(max_length=200,null=True) op3 = models.CharField(max_length=200,null=True) op4 = models.CharField(max_length=200,null=True) ans = models.CharField(max_length=200,null=True) class userQuizInfo(models.Model): username = models.ForeignKey(User, on_delete=models.CASCADE,null=True) quiz = models.ForeignKey(Quizzes, on_delete=models.CASCADE,null=True) correct = models.IntegerField(null=True) wrong = models.IntegerField(null=True) questOrder = models.CharField(max_length=10,null=True) views.py questions = list(QuestionList.objects.filter(quiz_id=pk)) questions = random.sample(questions,1) # userInfo = userQuizInfo.objects(pk=pk) # userInfo.questOrder += … -
Is there a way to EDIT databases (sqlite) in VSCode?
I am currently trying toed the database that comes with Django. Im tryin to use the VSCode Extension vscode-sqlite to edit the database. While I currently am able to look at the database without the gibberish that shows up when I try to open the database in a text editor, I can't find a way to actually edit the database. I think the buttons on the upper right corner of the UI might have something to do with whatever Im trying to achieve, but I dont really know what they do. Any help would really be appreciated. the unexplained buttons -
How to list available filters in drf for given api?
Is there a way to list all available filter/s for given api endpoint? -
How to use Django variable in JavaScript /jQuery?
I am passing a list of name subject in my HTML template from views.py but it's not working the way its working when I pass a list statically. Also, It's by default converting into Unicode (that I don't want) Following is my code, var data = "{{subject}}"; console.log("data before for loop",data) var i; for (i = 0; i<data.length; i++) { data = data.replace("&#39;", "'"); } console.log("data after for loop",data) var t2 = ['IT', 'Maths', 'History', 'Civics', 'Virtualization', 'BIO', 'EH', 'Chemistry']; console.log(typeof data); console.log(typeof t2) and following is the output of console.log, data before for loop [&#39;IT&#39;, &#39;Maths&#39;, &#39;History&#39;, &#39;Civics&#39;, &#39;VWE&#39;, &#39;BIO&#39;, &#39;EH&#39;, &#39;EHas&#39;] data after for loop ['IT', 'Maths', 'History', 'Civics', 'VWE', 'BIO', 'EH', 'EHas'] string object I want to know why it's not working.. and how can I make it work.. Thanks. -
Access Django M2M values in queryset without looping
I receive some data through Ajax that allows me to do some filtering on a model that has some m2m relations (say Model). I get a queryset, say "content" that I then need to send back using json. Here are simplified lines of code: content = Models.objects.all() content = content.values return JsonResponse({"data":list(content)}) It was working fine but the project changed and I now need to include the values of some of the m2m related models attached to Model to each queryset result instances, problem is that content=Model.objects.all() will of course not give me these values without some looping so I am stuck. I remember using a depth option in DRF that would have done the job here but unfortunately I cannot do this now as the project is too advanced and live. Any way to add directly in the queryset the results of the m2m related values ? Many many thanks -
How to add custom permissions to Django admin Groups page?
I want to create a Group that contains multiple custom permissions related to a custom Account model (extended from base User), then restrict access to routes/pages to Accounts only within that group. I have added the following custom permissions to my Account model (which is a working extension of the base AUTH_USER_MODEL)... class Account(models.Model): date_created = models.DateTimeField(auto_now_add=True, verbose_name='Date Created') date_modified = models.DateTimeField(auto_now=True) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.PROTECT) class Meta: permissions = ( ("can_access_x_pages", "To provide access to X pages"), ("can_access_y_pages", "To provide access to Y pages"), ("can_access_z_pages", "To provide access to Z pages"), ) ... but those permissions do not show up on the "New Group" page on Django Admin: Based on this GeeksForGeeks article, once the permissions have been added, they should simply be displayed. Any idea what I am missing? This self-answered StackOverflow question from 2016 is the same issue, but that OP cited a bug in django-admin-view-permission as the problem, but that is all they wrote. Edit: I checked my Adminer view of the database, and I do not see the new permissions there, so I'm guessing that they have not been migrated?