Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Putting if else conditions in Django Rest Framework API View while searching
I was writing API with DRF and what I want is to change queryset, if the search will return no results. from rest_framework.generics import ListAPIView from rest_framework import filters from .models import Item from .serializer import ItemSerializer from .pagination import ItemPagination class SearchItemApi(ListAPIView): queryset = Item.objects.all() serializer_class = ItemSerializer filter_backends = [filters.SearchFilter] search_fields = ['name',] pagination_class = ItemPagination Here is the serializer: class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ('id', 'name',) And this APIView will show these results on the page: { "count": 2, "next": null, "previous": null, "results": [ { "id": 1, "name": "Blue Jeans", }, { "id": 2, "name": "Red Jeans", } ] } How can I add a condition to return other queryset, if the search will bring zero results? -
when I send the cookies from the front-end (nextjs-reactjs), at the back-end (django-rest-framework) I get an empty dictionary with request.COOKIES
in the nextjs getServerSideProps i send request to api with this code : const groups = await api.getGroups() and the getGroups is : const getGroups = async ()=>{ const { data } = await api.get("http://localhost:8000/group", {withCredentials: true}) return data } in the back-end i print the request.COOKIES but it retruns an empty dictionary I'm using JWT authentication in the dj-rest-auth -
How To Update Specific Model Field From Django View Before Saving A Form
So, How can I update some Model Fields automatic, without the user having to input the values? In Models: class Url(models.Model): long_url = models.CharField("Long Url",max_length=600) short_url = models.CharField("Short Url",max_length=7) visits = models.IntegerField("Site Visits",null=True) creator = models.ForeignKey(CurtItUser,on_delete=models.CASCADE,null=True) def __str__(self): return self.short_url In Views: def home(request): """Main Page, Random Code Gen, Appendage Of New Data To The DB""" global res,final_url if request.method == 'POST': form = UrlForm(request.POST) if form.is_valid(): res = "".join(random.choices(string.ascii_uppercase,k=7)) final_url = f"127.0.0.1:8000/link/{res}" form.save() redirect(...) else: form = UrlForm return render(...) Sow how can for exapmle set from my view the value of short_url to final_url ??? -
Will I need to create separate HTTP methods(POST, PUT, DELETE) for ManyToManyField Operations - Django
I am having two tables group and action. class Group(models.Model): name = models.CharField() action = models.ManyToManyField(Action) class Action(models.Model): name = models.CharField() I have pre-defined data inserted into Group and Action table. My requirement is that, When I want to map Group table into Action table (Say for example "Mapping group to action(inserting to many to many table)","removing existing group to action mapping" ) I need to create Separate HTTP request for these Operation (POST, PUT, DELETE) or For single HTTP request(PUT) I can do these operations. Kindly help me on that. -
Can I create a Django Rest Framework API with Geojson format without having a model
I have a Django app that requests data from an external API and my goal is to convert that data which is returned as list/dictionary format into a new REST API with a Geojson format. I came across django-rest-framework-gis but I don't know if I could use it without having a Model. But if so, how? -
How to fix errors for Django's Auth/CustomUser after resetting the migrations and db?
After experimenting with setting up CustomUser and many-to-many relationships, I decided to make some (what turned out to be major) changes to the models. I had read that CustomUser/Auth needs to be set up first, or else it'll be a mess. But since I'm just learning and there was barely any data involved, I just went for it--not to mess up the CustomUser model intentionally, but I changed a model name--and (maybe this is the critical error) I updated the names everywhere it appeared. Now I'd deleted and reset the database, VENV folder, all the migration (along with __pycache__) files, and recreated test data so many times that I thought I could download the GitHub repo and set up a fresh new app easily again. But the app refuses to run and keeps asking for a missing table. Re-creating the app isn't my main concern-I'd like to understand what happened-what is this missing table (see the snippet of the error code)? AND: Why is a perfectly intact repo having the same issue with the missing table? Exception in thread django-main-thread: Traceback (most recent call last): File "/Volumes/Volume2/dev/lms6-v2/venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/Volumes/Volume2/dev/lms6-v2/venv/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 477, in execute … -
How to get multiple ajax functions to work correctly
I have a django template with two forms in it. When the first form is submitted, an ajax function is triggered and the second form is displayed on the page. When the second form is submitted, the ajax function linked to that form does not seem to work. For testing purposes, I tried to submit the second form before submitting the first form, and the ajax function works as expected. How do I make multiple ajax functions work correctly one after the other? This is my template <div class="form_container"> <div class="form"> <form action="{% url 'process_url' %}" method="post" id="youtube_link_form"> {% csrf_token %} <div class="input-group mb-3"> <input type="text" class="form-control youtube_link_input" placeholder="Put the youtube link or video id" aria-label="youtube_submit_input" aria-describedby="youtube_submit_button" name="youtube_submit_input"> <button class="btn youtube_submit_button" type="submit" id="youtube_submit_button">Submit</button> </div> </form> </div> </div> <div class="user_target_select"> <div class="target_buttons d-flex justify-content-between"> <form method="get" action="{% url 'user_select_positive' %}" id="positive_user_select_form"> <input type="hidden" id="positive_user_select_input" name="positive_user_select_input"> <button class="target_button btn btn-outline-success" id="user_select_positive" type="submit" data-bs-toggle="modal" data-bs-target="#thank_model">Positive</button> </form> </div> </div> Here, user_target_select div is hidden by default. When the first form is submitted, the div is displayed. This is my js file function youtube_link_form_submit(event) { event.preventDefault(); var data = new FormData($('#youtube_link_form').get(0)); $.ajax({ url: $(this).attr('action'), type: $(this).attr('method'), data: data, cache: false, processData: false, contentType: false, success: … -
How to get the sum of inlines in Django Admin
I want to show in admin the total money used in a computer by adding inline parts. models.py class Material(models.Model): name = models.CharField(max_length=30, null=False, blank=False) class Computer(models.Model): name = models.CharField(max_length=90) class UsedMaterial(models.Model): computer = models.ForeignKey(Computer, on_delete=models.SET_NULL, null=True) material = models.ForeignKey(Material, on_delete=models.SET_NULL, null=True) cost = models.DecimalField(max_digits=11, decimal_places=2, null=False, blank=False, default=0) quantity = models.IntegerField(null=False, blank=False, default=0) admin.py class UsedMaterialAdmin(admin.TabularInline): model = UsedMaterial def total(self, obj): return obj.cost * obj.quantity readonly_fields = ("total",) fields = ("material", "cost", "quantity", "total" ) @admin.register(Computer) class ComputerAdmin(admin.ModelAdmin): inlines = [UsedMaterialInline] fields = ("name",) I have found the way to show the total per article in the inline as you can see show Screen shot But how do I get the total of all the materials in the inline? -
How can I refresh another page in Django?
Is there any way to refresh another page by clicking a button on current page? (Any way for server to send a packet that makes every broswer on a certain url page refresh itself) example: 127.0.0.1:8000/main -> a page that has the button 127.0.0.1:8000/list -> a page I want to refresh My desktop web browser is currently on '/main' and my laptop web browser is currently on '/list'. How can I refresh my labtop web browser(to a newer version of '/list'page) by clicking a button in '/main' page on my desktop? Is using websocket(like django-channels) only way to do this work? -
How can I connect to the IPFS network using web3.storage API in Django?
Web3.Storage site can be used to upload files, but it's also quick and easy to create and run a simple upload script — making it especially convenient to add large numbers of files. The script contains logic to upload a file to Web3.Storage and get a content identifier (CID) in return which would basically be the address to access files. However, in the documentation, the in-built functions are given using Node.js. How can this be done using Django or any other Python based framework? -
Separating files based on file extension?
I want to separate the files in my models based on extension type. Right now I am able to print all the files but now i want to separate them based on extension and apply separate funtions based on the extensions. The code in my models.py class File(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=100) doc = models.FileField(upload_to='files/docs/', validators=[FileExtensionValidator(allowed_extensions=['pdf','docx'])]) and my code in view.py def file_p(): for file in File.objects.all(): print(file.doc) I am getting an output something like this. files/docs/12.6.1-packet-tracer---troubleshooting-challenge---document-the-network_1s00TUA.docx files/docs/12.6.1-packet-tracer---troubleshooting-challenge---document-the-network_z9b2tyh.pdf How can i separate them based on extension so that i can apply further functions based on the file type. -
Custom Decorator for Django admin.ModelAdmin to Append Actions
I'm trying to create an "export model to csv in admin panel" function and append it to actions in admin.ModelAdmin. By selecting a few rows in a table in the admin panel, the goal is to export the selected rows to csv. However, my current code in decorators.py::exportable_model didn't achieve my goal. Versions: Python: 3.10 Django: 4.0.4 mixins.py import csv import codecs from django.http import HttpResponse class ExportCsvMixin: # ref: https://books.agiliq.com/projects/django-admin-cookbook/en/latest/export.html def export_as_csv(self, request, queryset): meta = self.model._meta field_names = [field.name for field in meta.fields] response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename={}.csv'.format(meta) # To export CN characters. Ref: https://stackoverflow.com/a/63242835/16450509 response.write(codecs.BOM_UTF8) writer = csv.writer(response) writer.writerow(field_names) for obj in queryset: row = writer.writerow([getattr(obj, field) for field in field_names]) return response export_as_csv.short_description = "Export Selected (.csv)" admin.py @exportable_model(export_format="csv") @admin.register(ParticipantType) class ParticipantTypeAdmin(admin.ModelAdmin, ExportCsvMixin): list_display = [field.name for field in ParticipantType._meta.get_fields()] @exportable_model(export_format="csv") @admin.register(PropsEventType) class PropsEventTypeAdmin(admin.ModelAdmin, ExportCsvMixin): list_display = [field.name for field in PropsEventType._meta.get_fields()] @exportable_model(export_format="csv") @admin.register(LimitedTimeEventType) class LimitedTimeEventTypeAdmin(admin.ModelAdmin, ExportCsvMixin): list_display = [field.name for field in LimitedTimeEventType._meta.get_fields()] Tentative decorators.py, which references the coding style in register function in @admin.register (from django.contrib import admin): def exportable_model(export_format: str): from django.contrib.admin import ModelAdmin from .mixins import ExportCsvMixin def _decorator(admin_class): if not issubclass(admin_class, ModelAdmin): raise ValueError("Wrapped class must subclass ModelAdmin.") actions … -
Django Deploy ElasticBeanstalk AWS error creating Enviroment
Im trying to deploy my django application at EB since I failed with django django.config file: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: store/wsgi.py Note: My normal python Virtual Env the python Version is 3.9.12 but when i run eb init -p python-3.9.12 store it doesent get recognized, even if i just set as: eb init -p python-3.9 store so i did eb init -p python-3.8 store and it worked Also at the full log, it choose atumatcally the region,how can i change that? I ran eb create store-env Error Log: 2022-04-22 04:04:14 ERROR Instance deployment failed. For details, see 'eb-engine.log'. 2022-04-22 04:04:16 ERROR [Instance: i-0e999ebdfd96bb4d9] Command failed on instance. Return code: 1 Output: Engine execution has encountered an error.. 2022-04-22 04:04:16 INFO Command execution completed on all instances. Summary: [Successful: 0, Failed: 1]. 2022-04-22 04:05:19 ERROR Create environment operation is complete, but with errors. For more information, see troubleshooting documentation. ERROR: ServiceError - Create environment operation is complete, but with errors. For more information, see troubleshooting documentation. The full log: Creating application version archive "app-220422_005816740583". Uploading: [##################################################] 100% Done... Environment details for: store-env Application name: store Region: us-west-2 Deployed Version: app-220422_005816740583 Environment ID: e-7rraydvprc Platform: arn:aws:elasticbeanstalk:us-west-2::platform/Python 3.8 running on 64bit Amazon Linux 2/3.3.12 … -
django - 'module' object does not support item assignment
When clicking the like button on a article the following error shows up: 'module' object does not support item assignment and it leads to this piece of code: def get_context_data(self, *args,**kwargs): stuff = get_object_or_404(Article, id=self.kwargs['pk']) #grab article with pk that you're currently on total_likes = stuff.total_likes() context["total_likes"] = total_likes return context but when I remove this piece the feature works fine but you cant see the likes - the only way you know its working is if you go into django admin and see which user is highlighted. my articles views.py: class ArticleDetailView(LoginRequiredMixin,DetailView): model = Article template_name = 'article_detail.html' def get_context_data(self, *args,**kwargs): stuff = get_object_or_404(Article, id=self.kwargs['pk']) #grab article with pk that you're currently on total_likes = stuff.total_likes() context["total_likes"] = total_likes return context def LikeView(request, pk): article = get_object_or_404(Article, id=request.POST.get('article_id')) article.likes.add(request.user) #might need check later return HttpResponseRedirect(reverse('article_detail', args=[str(pk)])) my articles models.py: class Article(models.Model): title = models.CharField(max_length=255) body = RichTextField(blank=True, null=True) #body = models.TextField() date = models.DateTimeField(auto_now_add=True) likes = models.ManyToManyField(get_user_model(), related_name='article_post') author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) def total_likes(self): return self.likes.count() def __str__(self): return self.title def get_absolute_url(self): return reverse('article_detail', args=[str(self.id)]) full error pic: -
Item could not be retrieved UNAUTORIZED (HEROKU)
I simply want to deploy my django app on heroku and getting this little pop up on top-right corner. tried almost all solutions given by heroku help still stuck with this error. Please Help! -
How to ignore special characters from the search field in Django
The model is something like class Product(BaseModel): name = models.CharField(db_column='name', max_length=200, blank=False, null=False, unique=True) View is class ProductViewSet(BaseViewSet): queryset = Product.objects.all() ... filterset_class = ProductFilter The filter is class ProductFilter(django_filters.FilterSet): search = django_filters.CharFilter(field_name='name', lookup_expr='icontains') class Meta: model = Product fields = [] Now.. if the name field has a value something like "This is a/sample" and search text is "asample". I would like to return that row. Thanks in advance. -
How to optimize data scrape
I am scraping data from an external API to my database on Django. This method is taking a very long time to load. Is there a better way to do this? Here is the code from my views.py file: def market_data(request): # GET MARKETPLACE ASKS NFT_list = {} URL = '...&page_number=1' response = requests.get(URL).json() pages = response['result']['page_count'] page_index = 1 for page in range(pages): URL = "...&page_number="+str(page_index) response = requests.get(URL).json() nfts = response['result']['ask_summaries'] for item in nfts: if NFT.objects.filter(nft_data_id = ['nft_data_id']).exists(): pass else: nft_data = NFT( nft_data_id = item['nft_data_id'], brand = item['brand'], price_low = item['price_low'], price_high = item['price_high'], nft_count = item['nft_count'], name = item['name'], series = item['series'], rarity = item['rarity'], ) nft_data.save() NFT_list = NFT.objects.all() page_index += 1 return render(request, 'main/market_data.html', {'NFT_list' : NFT_list} ) -
Django for loop in Carousel
I'm trying to add a title to each slide in a dynamic carousel in Django. I have the images functioning properly and working as expected. The title is stacking on the first slide and as it progresses towards the end it removes a title and once it reaches the end it has only one title and it is correct. What would be the best way to fix this? html <div id="CarouselWithControls" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> {% for item in carousel_items %} {% if forloop.first %} <div class="carousel-item {% if forloop.first %} active {% endif %}"> <img src="{{ item.carousel_picture.url }}" class="d-block w-100"> </div> <div class="carousel-caption d-none d-sm-block"> <h5 class="text-white">{{ item.carousel_title }}</h5> </div> {% else %} <div class="carousel-item {% if forloop.first %} active {% endif %}"> <img src="{{ item.carousel_picture.url }}" class="d-block w-100"> </div> <div class="carousel-caption d-none d-sm-block {% if forloop.first %} active {% endif %}"> <h5 class="text-white">{{ item.carousel_title }}</h5> </div> {% endif %} <a class="carousel-control-prev" href="#CarouselWithControls" role="button" data-bs-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#CarouselWithControls" role="button" data-bs-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> {% endfor %} views.py def gallery(request): carousel_items = CarouselItem.objects.all() context = {'carousel_items': carousel_items} return render(request, 'home/gallery.html', context=context) models.py class CarouselItem(models.Model): carousel_title = models.CharField(max_length=200 , blank=True, null=True) … -
Django pymongo search, sort, limit on inner array and count them
I am learning Django with MongoDb and have a collection to search into. Here is a sample document in the collection: { "_id": { "$oid": "62615907568ddfca4fef3a25" }, "word": 'entropy, "count": 4, "occurrence": [ {"book": "62615907568ddfca4fef3a23", "year": 1942, "sentence": 0 }, {"book": "62615907568ddfca4fef3a23", "year": 1942, "sentence": 5 }, {"book": "62615907568ddfca4fef3a75", "year": 1928, "sentence": 0 }, {"book": "62615907568ddfca4fef3a90", "year": 1959, "sentence": 8 } ] } I want to retrieve the array elements of 'occurrence' field of a specific document (word): Sorted by year Within an year range Limited with offset count the total results (without limit/offset) What I have done so far is: offset= 0 limit= 10 search= {'$and': [{"_id": word_id_obj, "occurrence": {"$elemMatch": {"year": {"$gte": 1940, "$lte": 1960}}}}]} word_docs= wordcollec.aggregate([ {"$match": search}, {"$project": {"occurrence": {"$slice": ['$occurrence', offset, limit]} } }, {"$sort": {'occurrence.year': -1}} ]) # Count total results recnt= wordcollec.aggregate([{"$match": search}, {'$group' : {"_id": "$_id", "sno" : {"$sum" : {"$size": "$occurrence"}}}}]) The year range, count are not working and I am unable to sort them. How can I rewrite my query for this? Thanks in advance. -
Detecting changes in file without restarting Python application (Django APP)
I'm using Django, I want my web page to see the changes I've made to the JSON file as the web page is refreshed. When I close and open Django, the features I added to the json file or I changed it see some settings, but I don't want this, it needs to see the changes instantly -
django traceback errors manage.py
I am new to Django and followed a tutorial to set up my venv now I am trying to startserver using manage.py I have sqlit3 installed and running when I run the following command python manage.py startserver I receive the following error in the picture I have tried fixing my settings.py and other cofigs and also reinstalling the python libs but nothing is working please help. -
Django channels group_send not passing the event messages in Test environment
I have a Django Channels consumer receive function like the following: async def receive(self, text_data=None, bytes_data=None): ## Some other code before await self.channel_layer.group_send( self.room_name, { 'type': 'answered_users_count', 'increment_answer_id': 15, }, ) The answered_users_count function goes like this: async def answered_users_count(self, event): print(event) increment_answer_id = event['increment_answer_id'] await self.send( text_data=json.dumps({ 'meant_for': 'all', 'type': 'answer_count', 'data': { 'increment_answer_id': increment_answer_id } }) ) The whole thing works fine with python manage.py runserver, where the print(event) also prints the following dictionary into the command line: {'type': 'answered_users_count', 'increment_answer_id': 15} However, this part of the consumer does not work when it comes to running the unit test that I have written for it. Here's the unit test that I've written for testing the above code: class SampleConsumerTest(TransactionTestCase): async def test_channel(self): communicator = WebsocketCommunicator(application, "/ws/walk/qa_control/12/") connected, subprotocol = await communicator.connect() self.assertEqual(connected, True) await communicator.send_to(json.dumps({ "abc": "xyz" })) raw_message = await communicator.receive_from() message = json.loads(raw_message) When I run the above test case by using python manage.py test, it fails. I figured out that the cause of this is that the event given as the input to answered_users_count does not carry the field increment_answer_id in the test execution. I got to know about this because the print(event) line in … -
Fit Layout to any screen
I have tried to make it responsive but it appears like the image I shared.I used bootstraps owl carousel to make image-slider it doesn't fit to screens larger or smaller than my laptop.I make containers and they are also not responsive even the footer moves here and there and is not stickyI tried everyway to make these 3 things appear responsive at a same time but I can't do that.It also has css.min CSS file. This is what it is showing when I check responsiveness *{ padding: 0; margin: 0; box-sizing: border-box; } html{ height: 100%; } .body{ display: flex; min-height: 100%; } .container1{ position: relative; width:1500px; display: flex; justify-content: center; align-items: center; flex-wrap: wrap; padding: 30px; margin-top: 8%; } .container1 .card1{ background: rgb(70, 218, 203); width: 308px; position: relative; height: 400px; margin: 30px 20px; padding: 20px 15px; display: flex; flex-direction: column; flex-wrap: nowrap; box-shadow: 0.5px 10px rgb(0, 217, 255); transition: 0.3s ease-in-out; margin-top: 5%; } .container1 .card1 .imgbx{ position: relative; width: 260px; height: 260px; top: -80px; left:20px; box-shadow: 0 5px 20px rbga(0,0,0,1.2); } .container1 .card1 .imgbx img{ max-width: 100%; margin-left: 20px; border-radius: 10px; padding-top: 20px; } .imgbx:hover img{ transform:scale(1.1); } .navbar{ background-color: #30d5b9dc !important; } .navbar .navbar-brand{ color: white; … -
putting dictionary values inside a table in Django template
Its my first time using Django template. I'm trying to make a table inside my page with values from a dictionary that I built consuming an API. Here is how I'm sending the data inside my views.py: data = { "year_most_launches": result_launches, "launch_sites":response_sites, "launches_2019_2021":response_2019_2021 } return render(request,"main/launches.html", {"data":data}) Here is how it is my html page: <table class="table"> <thead> <tr> <th>Year with most launches</th> <th>Launch site with most launches</th> <th>Number of launches between 2019 and 2021</th> </tr> </thead> <tbody> <tr> <td>{{ data["year_most_launches"] }}</td> <td>{{ data["launch_sites"] }}</td> <td>{{ data["launches_2019_2021"] }}</td> </tr> </tbody> </table> But I'm getting the following error django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '["year_most_launches"]' from 'data["year_most_launches"]' How can I solve this? Can someone help? -
Filtering in Django which depends on first field
>Suppose I have 3 fields of a Car Shop. those are Condition, Brand, Model . class Car(models.Model): ConditionType=( ('1','New'),('2','Used'),('3','Reconditon') ) BrandType=( ('Toyota','Toyota'),('Honda','Honda'),('Mitsubishi','Mitsubishi'), ('Nissan','Nissan'),('Hyindai','Hyindai')) >now model will depends on Brand user select . if user select Toyota as brand then >available model for toyota are (Axio,Premio ,Allion etc) ,for Honda carmodels are (civic >,vezel,Grace) Condition=models.CharField(max_length=120,choices=ConditionType,default='New') Brand=models.CharField(max_length=120,choices=BrandType,default=None) Condition=models.CharField(max_length=120,choices=ConditionType,default='New') CarModel=models.CharField(max_length=120,choices=ModelType,default=None) Now how can I make carmodel dependent on Brand . Suppose if user choose Brand - Toyota >then user can only choose Carmodel of Toyota if user Choose Honda than he can choose >CarModel of Honda . which means how can I make my model selection dependent on Brand ? if no brand is selected than user won't able to choose CarModel .**