Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save a ModelSerializer with a foreign Key in Django Rest Framework
I have these serializers class OwnerSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ 'id', 'name' ] class PetSerializer(serializers.ModelSerializer): owner = OwnerSerializer() class Meta: model = Pet fields = [ 'id', 'name', 'owner' ] def create(self, validated_data): """ Create and return a new `Pet` instance, given the validated data. """ owner_data = validated_data.pop('owner', None) if owner_data: owner = User.objects.get(**owner_data)[0] validated_data['owner'] = owner return Pet.objects.create(**validated_data) This is my ViewSet: class PetViewSet(viewsets.ModelViewSet): """ ModelViewSet for model pets """ queryset = Pet.objects.all() serializer_class = PetSerializer def create(self, request, *args, **kwargs): request.data['owner'] = {'id': request.user.id, 'name': request.user.name} pet_serializer = self.get_serializer(data=request.data) pet_serializer.is_valid(raise_exception=True) self.perform_create(pet_serializer) headers = self.get_success_headers(pet_serializer.data) return Response(pet_serializer.data, status=status.HTTP_201_CREATED, headers=headers) But when storing it, all the data is saved, but in the created function the owner object does not arrive, it is shown as 'owner': OrderedDict ()} So when I return the saved object, I get it with the owner with the default id, although the user I get in the view is 'owner': {'id': 10, 'name': 'My name'}} ): My Json Response: { "id": 26, "name": "My pet", "owner": { "id": 1 } } What am I doing wrong? Thank you -
Web Based Place Finder Using Django and GeoDjango
I'm currently working on this django project and I want users to be able to see a google map tracing from their current location to the destination they would select which would be added by the admin. How would I go about it and can I get a sample code for the exactly? -
Django Uploading Image through forms.py and The 'image' attribute has no file associated with it
I'm using django and made forms.py to upload the post. When I upload the post through admin page, they save image file well and I can see whole post in the page. But when I upload the post with form what I made, there's problem. They don't save image and give this message. 'The 'image' attribute has no file associated with it.' with The Value error. How can I solve this problem? And why it cannot save my file through forms.py but works in admin? posting.html <form method='POST' enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type='submit'>Submit</button> </form> models.py from django.db import models from taggit.managers import TaggableManager from django.utils import timezone # Create your models here. class Post(models.Model): title = models.CharField(max_length=100) image = models.ImageField(upload_to='images', null=True, blank=True) content = models.CharField(max_length=300) score = models.DecimalField(max_digits=3, decimal_places=1) tags = TaggableManager() date = models.TimeField(default=timezone.now) def __str__(self): return self.title views.py def posting(request): if request.method == 'POST': form = PostingForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/posting/') else: print(form.errors) else: form = PostingForm() return render(request, 'posting/posting.html', {'form':form}) -
Could I forward a stream from my website to youtube through their API?
I'm making a website for my church so we don't have to miss services and kids don't have to miss their classes during this pandemic and I made it so we can stream directly to the website but we can't stream to both the website and youtube at the same time since both require either an encoder or a webcam. Do you think I'd be able to somehow emulate an encoder to stream to youtube as well? I don't need help coding it, I just need to know if you think it's possible and if it is, if I should code a package so others can do the same. If I can help give other developers a bigger tool belt, I will. Through some modification of django-encode it may work. I don't think it's against their Terms of Service but I'll do more reading into that. -
Cannot assign OrderedDict...must be a Address instance
Trying to have a serializer to save address dict but receive the next error message: Cannot assign \"OrderedDict([('state', 'ON'), ('location', {'lat': '43.644905', 'long': '-79.399437'}), ('street1', '580 King St. W.'), ('street2', ''), ('city', 'Toronto'), ('postalcode', 'M5V 1M3'), ('country', 'US')])\": \"Venue.address\" must be a \"Address\" instance. Here are my serializers: class AddressSerializer(serializers.ModelSerializer): id = serializers.IntegerField(required=False) state = serializers.CharField(allow_blank=True) location = serializers.JSONField(required=False) class Meta: model = Address fields = "__all__" class VenueSerializer(serializers.ModelSerializer): address = AddressSerializer(many=False) image = serializers.JSONField(source="images", required=False) class Meta: model = Venue fields = ["id", "hostedbyid", "slug", "name", "image", "address"] extra_kwargs = {"id": {"validators": []}} def create(self, validated_data): address_data = validated_data.pop("address") try: validated_data["address"] = Address.objects.get(street1=address_data.get("street1")) except Address.DoesNotExist: validated_data["address"] = Address.objects.create(**address_data) try: venue = Venue.objects.get(pk=validated_data.get("id")) except Venue.DoesNotExist: venue = Venue.objects.create(**validated_data) return venue Models are here: class Address(models.Model): id = models.IntegerField(primary_key=True) street1 = models.TextField() street2 = models.TextField(blank=True, null=True) city = models.TextField() state = models.TextField() postalcode = models.TextField() country = models.TextField() location = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'address' class Venue(models.Model): id = models.IntegerField(primary_key=True) hostedbyid = models.IntegerField(blank=True, null=True) slug = models.TextField() name = models.TextField(blank=True, null=True) images = JSONField() address = models.ForeignKey(Address, models.DO_NOTHING, blank=True, null=True) class Meta: managed = False db_table = 'venue' And here is the sample data I want … -
How can we use log4j in Django api?
i make a rest api with Django. And i want to use log4j in same project. How can i do that? is this possible? you can share article, video or anything with me Thanks. -
Count the failed login attemps and lockout user in Django
I am trying to count the number of invalid login attempts using "user_login_failed_callback" method. As shown the code below, I am trying to access previous database field value of "failed_login_count" from "user_login_failed_callback" method. I will update the value of failed_login_count to failed_login_count+1 and also update the date and time to current time. My questions are So could you please let me know how can I access failed_login_count from database and update the existing value. As shown in below code I am using "BruteForceEntry.objects.filter" to update existing database row. So is this the correct way to update table. How can I lock out user account after more than 10 failed login attemps. Could you please help me. class BruteForceEntry(models.Model): user = models.ForeignKey(User, unique=True) username = models.CharField(max_length=256, null=True) data_time_of_last_unsuccessful_login = models.DateTimeField(auto_now=True, blank=True) failed_login_count = models.IntegerField(default=0) def __unicode__(self): return '{0} - {1} - {2}'.format(self.username, self.data_time_of_last_unsuccessful_login, self.failed_login_count) def __str__(self): return '{0} - {1} - {2}'.format(self.username, self.data_time_of_last_unsuccessful_login, self.failed_login_count) @receiver(user_login_failed) def user_login_failed_callback(sender, credentials, **kwargs): username = credentials['username'] user = User.objects.get(username=username) profile = user.get_profile() failed_login_count = profile.failed_login_count + 1 BruteForceEntry.objects.filter(username=username).update(data_time_of_last_unsuccessful_login=timezone.now(), failed_login_count=failed_login_count) -
passing link in django template
i am passing a variable in django template named "link". This is my code snippet in views.py link = "msdetail/{{item.post_id}}" return render(request, "mart/all-products.html", {'t': ms, 'cat':category, 'link':link}) and on html file : <a href={% url '{{link}}' %} class="btn btn-primary">View</a> it is giving this error : "NoReverseMatch at /mart/menshirt Reverse for '{{link}}' not found. '{{link}}' is not a valid view function or pattern name."..... the error happens when i click the button. can i not pass url like this or is it some other issue? -
Adding a field into Django REST with no field on serializer instance
I have 3 models: Post, Topic, PostTopic. PostTopic contains all the topics related to the Post. The models look like this: class Topic(models.Model): name = models.CharField(max_length=25, unique=True) def save(self, *args, **kwargs): topic = Topic.objects.filter(name=self.name) if topic: return topic[0].id super(Topic, self).save(*args, **kwargs) return self.id class PostTopic(models.Model): topic = models.ForeignKey(Topic, on_delete=models.CASCADE) post= models.ForeignKey(Post, on_delete=models.CASCADE) The Topic model cannot have 2 topics that are the same. Here's how my serializer looks like: class PostSerializer(serializers.ModelSerializer): topics = serializers.ListField( child=serializers.CharField(max_length=256), max_length=3 ) class Meta: model = Post fields = ('user', 'status', 'topics') def create(self, validated_data): topics= validated_data.pop('topics') post = Post.objects.create(**validated_data) for topic in topics: topic_id = Topic(name=topic).save() PostTopic(post_id=post.id, topic_id=topic_id).save() return post However, I get an error saying: Got AttributeError when attempting to get a value for field topics on serializer PostSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Post instance. I understand what I'm doing wrong, but I'm not sure how I can fix it where I can save the topic in PostTopic too. Is there a better way to do this? -
Is there a way to
So my website allows users to upload images, which are then stored in media. However, I seem to be having problems getting code to find the location where the files have been uploaded. Settings.py ... # Media MEDIA_DIR = os.path.join(BASE_DIR, 'media') MEDIA_ROOT = MEDIA_DIR #os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' IMAGES_DIR = os.path.join(MEDIA_URL,"images") The problem is that i am recieving a file not found error: [Errno 2] No such file or directory: 'media/images/usruploads/brownie_ZNORYtU.jpg' Request Method: POST Request URL: http://127.0.0.1:8000/add_recipe/ Django Version: 2.2.3 Exception Type: FileNotFoundError Exception Value: [Errno 2] No such file or directory: 'media/images/usruploads/brownie_ZNORYtU.jpg' Exception Location: C:\Users\natha\Envs\spatula\lib\site-packages\PIL\Image.py in save, line 1991 Python Executable: C:\Users\natha\Envs\spatula\Scripts\python.exe Python Version: 3.7.5 Python Path: ['C:\Users\natha\OneDrive\Documents\GitHub\spatula\spatula_project', 'C:\Users\natha\Envs\spatula\Scripts\python37.zip', 'C:\Users\natha\Envs\spatula\DLLs', 'C:\Users\natha\Envs\spatula\lib', 'C:\Users\natha\Envs\spatula\Scripts', 'C:\Users\natha\AppData\Local\Programs\Python\Python37\Lib', 'C:\Users\natha\AppData\Local\Programs\Python\Python37\DLLs', 'C:\Users\natha\Envs\spatula', 'C:\Users\natha\Envs\spatula\lib\site-packages'] However visual studio is showing the files to be stored in media/media/images/usruploads/ Which is strange as I dont understand where the second /media/ is coming from. I guess my question is can anyone help me sort out the models and settings file so that url's are mapped to /media/images/usruploads/ The current Image model is: class Image(models.Model): def images_path(): return os.path.join(settings.IMAGES_DIR, 'usruploads') def resize(self): # FileNotFoundError occurring on this line due to PIL not finding file im = PIL.Image.open(self.image) size=(200,200) out = im.resize(size) … -
How to make different Django form input buttons display on same line
I am using two separate Django forms on a page I am working on and I am wanting the input buttons to show up on the same line. Currently, they are stacking. I tried using CSS styling to use the inline-block but I don't think that's working because they are in separate forms. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Title</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link rel="stylesheet" href="song_edit.css" /> </head> <body> <form method="POST" id="form1"> {% csrf_token %} <li>{{ file_name }}</li> <li>{{ form.as_p }}</li> <input type="submit" class="btn btn-primary" value="Download" name="save" id="download" /> </form> <form action="/path/" method="get" id="form2"> <input type="submit" class="btn btn-secondary" name="next" value="Next" id="Next" /> </form> </body> </html> Fiddle -
get label text from model to template django
I have this model class Image(models.Model): image = models.ImageField(upload_to=multi_image_path, blank=True, null=True) product_id = models.IntegerField() I want to print this model labels in the templates, example: I want it to be printed dynamically not manually -
Django url by category slug
I need two ways to categorize my posts in Django. First one is by School, and second one is by type of wellness(physical/mental etc) models.py from django.db import models from django.db.models.signals import pre_save from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from ckeditor.fields import RichTextField from ckeditor_uploader.fields import RichTextUploadingField from PIL import Image class Category(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=100, unique=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name class School(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=100, unique=True) class Meta: ordering = ('name',) verbose_name = 'school' verbose_name_plural = 'schools' def __str__(self): return self.name class VideoPost(models.Model): category = models.ForeignKey('Category', on_delete=models.CASCADE) school = models.ForeignKey('School', on_delete=models.CASCADE) title = models.CharField(max_length=100) slug = models.SlugField(max_length=100, unique = True) author = models.ForeignKey(User, on_delete=models.CASCADE) video = models.CharField(max_length=100, blank=True) content = RichTextUploadingField() image = models.ImageField(upload_to='images', null=True, blank=True) date_posted = models.DateTimeField(default=timezone.now) def _get_unique_slug(self, *args, **kwargs): self.slug = slugify(self.title) super(VideoPost, self).save(*args, **kwargs) def __unicode__(self): return self.title views.py from django.shortcuts import render, get_object_or_404 from django.utils import timezone from .models import VideoPost from .forms import PostForm from django.shortcuts import redirect # Create your views here. def post_list(request): posts = VideoPost.objects.order_by('-date_posted') return render(request, 'stories/browse.html', {'posts': posts}) def post_detail(request, post_slug): # post = … -
django export large excel queryset
I have a relatively large queryset and i want to export it into excel file i was useing the XLWT library and django streaming response with csv file. when i export very large queryset of a table in sqldeveloper or navicat, the export operation is very fast but django's libraries is relatively slow. i think the excel write by row and column, or csv streaming response, write row by row in file but i looking for a way to write whole of queryset to excel. is there a way to export whole of queryset to excel in python django? Something that comes to my mind is call os command in python code to run export command in database but i not tested it. thanks everybody -
Django model saves rare string when field has choices
I have the following models: class Service(CustomModel): item = models.ForeignKey('inventory.ProductItem', on_delete=models.PROTECT, related_name='services', verbose_name=_("Artículo")) reference = models.ForeignKey('operations.Sale', on_delete=models.PROTECT, related_name='services', verbose_name=_("Referencia")) client_name = models.CharField(max_length=100, verbose_name=_("Nombre del Cliente")) client_phone = models.CharField(max_length=10, verbose_name=_("Teléfono del Cliente")) comment = models.TextField(verbose_name=_("Observaciones")) class Meta: verbose_name = _("Servicio") verbose_name_plural = _("Servicios") def __str__(self): return "[{}] {}/{}/{}".format(self.id, self.client_name, self.item.serial_number, self.item.product.name) def save(self, *args, **kwargs): new = False if self.id else True super().save(*args, **kwargs) if new: initial_status = ServiceStatus() initial_status.service_id = self.id initial_status.status = SERVICE_STATE_RECEIVED, initial_status.save() SERVICE_STATE_RECEIVED = 'RECEIVED' SERVICE_STATE_WAITING_FOR_ASSESSMENT = 'WAITING_FOR_ASSESSMENT' SERVICE_STATE_WARRANTY = 'WARRANTY' SERVICE_STATE_QUOTED = 'QUOTED' SERVICE_STATE_SCHEDULED = 'SCHEDULED' SERVICE_STATE_REPAIRING = 'REPAIRING' SERVICE_STATE_DOWN = 'DOWN' SERVICE_STATE_FINISHED = 'FINISHED' SERVICE_STATE_DELIVERED = 'DELIVERED' SERVICE_STATE_CHOICES = ( (SERVICE_STATE_RECEIVED, _("Recibido")), (SERVICE_STATE_WAITING_FOR_ASSESSMENT, _("En Evaluación")), (SERVICE_STATE_WARRANTY, _("En Garantía")), (SERVICE_STATE_QUOTED, _("Cotizado")), (SERVICE_STATE_SCHEDULED, _("Programado")), (SERVICE_STATE_REPAIRING, _("En Reparación")), (SERVICE_STATE_DOWN, _("Baja")), (SERVICE_STATE_FINISHED, _("Servicio Concluido")), (SERVICE_STATE_DELIVERED, _("Entregado")), ) class ServiceStatus(CustomModel): service = models.ForeignKey(Service, on_delete=models.PROTECT, related_name='status', verbose_name=_("Servicio")) status = models.CharField(max_length=25, choices=SERVICE_STATE_CHOICES, verbose_name=_("Estatus")) timestamp = models.DateTimeField(auto_now=True, verbose_name=_("Fecha y Hora")) comment = models.TextField(null=True, blank=True, verbose_name=_("Comentarios")) update = False class Meta: verbose_name = _("Estado del Servicio") verbose_name_plural = _("Estados de los Servicios") def __str__(self): return "[{}] {}/{}/{}".format(self.id, self.service.id, self.status, self.timestamp) As you can see, when a Service instance is created, it automatically creates an instance of ServiceStatus, but field ServiceStatus.status gets a wefgdsird value: … -
Django: render multiple sections
I was struggling to come up with a more correct title for this question, so if anyone has a suggestion after I describe my problem I'll gladly update it. I'm using Django to create my pages(with python in backend). One of such pages has 4 tabs in it. Some tabs require longer backend processing, but I don't want the page to wait for each tab, instead I want each tab to be displayed as soon as it is ready. So far I used rest api for each tab and then created the whole tab in js. But I like using Django templates much better. Is there a way to have to it so that I can still create each tab in Django templates? <div class="tab-content"> <div id="tab1" class="tab-pane fade in active"> {% include 'my_project/tab1.html' %} </div> <div id="tab2" class="tab-pane fade"> {% include 'my_project/tab2.html' %} </div> <div id="tab3" class="tab-pane fade"> {% include 'my_project/tab3.html'%} </div> <div id="tab4" class="tab-pane fade"> {% include 'my_project/tab4.html'%} </div> I have single URL, I want this URL to invoke 4 backend views handler to render each of the tab htmls. -
Django Fullcalendar modal
I'm building fullcalendar that will manage events in my django app. The problem that I'm facing here is that modal is opened on dayClick event, but when fields are filled and submit button is clicked nothinh happens (modal is not closed and event is not added, when I opend the modal for the second time then the data is already filled with what I've previously typed and new event is added). I'm using this js code: var calendar = $('#calendar').fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'month,agendaWeek,agendaDay' }, events: [ {% for event in events %} { title: "{{ event.patient }}", start: '{{ event.start|date:"Y-m-d h:m" }}', end: '{{ event.end|date:"Y-m-d h:m" }}', type: "{{ event.type }}", notes: "{{ event.notes }}", id: '{{ event.id }}', }, {% endfor %} ], selectable: true, selectHelper: true, editable: true, eventLimit: true, dayClick: function (start, end, allDay) { $("#modal-visit").modal("show"); var title = document.getElementById("patient").value; var start = document.getElementById("start").value; var end = document.getElementById("end").value; var type = document.getElementById("type").value; var notes = document.getElementById("desc").value; $.ajax({ type: "GET", url: '/add_event', data: {'title': title, 'start': start, 'end': end, 'type': type, 'notes': notes}, success: function (data) { $('#calendar').fullCalendar('renderEvent', {'title': title, 'start': start, 'end': end, 'type': type, 'notes': notes}); alert("Added Successfully"); }, failure: … -
Django models design for booking system
I have started recently some playing with Django and databases to get more familiar with this. I have some understanding o the subject, but I am unsure of one design choice I've made and I'd appreciate any comments/suggestions on that. My idea is to write simple app that will allow to book conference venues. Those can be either hotels or some stand alone conference rooms. In the hotel there is a chance that there are also rooms for sleeping and might also be restaurant/catering capability on-site. Moreover, one hotel or conference facility can have multiple conference rooms of different sizes. My current models design is following: class Service(models.Model): Name = models.CharField(max_length = 255) Address = models.CharField(max_length = 255) City = models.CharField(max_length = 100) PostalCode = models.CharField(max_length = 10) Country = models.CharField(max_length = 100) TelephoneNumber = models.CharField(max_length = 20) Website = models.CharField(max_length = 100) Email = models.CharField(max_length = 100) Description = models.TextField() def __str__(self): return self.Name class Catering(Service): MaxMeals = models.IntegerField() class Venue(Service): Catering = models.ForeignKey(Catering, on_delete = models.SET_NULL, blank = True, null = True) ProvidesSleeping = models.BooleanField() class RoomT(models.Model): Venue = models.ForeignKey(Venue, on_delete = models.CASCADE) OccupancyLimit = models.IntegerField() class HotelRoom(RoomT): RoomType = models.IntegerField() class ConferenceRoom(RoomT): HasProjector = models.BooleanField() I am … -
Pass value from loop to HTML - Django
My algorithm compares uploaded document with other documents and writes to output report like 'x part of uploaded document found in y document' and so on. Now I want to pass these reports to my HTML template but don't know how can assign value in for loop to some variable. Here is some part of my code: views.py: for each_file in files: other_docs = open(each_file, 'r') other_docs_words = other_docs.read().lower().split() for i in range(len(other_docs_words) - 4): for j in range(len(other_docs_words)+1): if(j-i == 5): each_five_others = other_docs_words[i:j] for original_each_five in iterate(): if(original_each_five == each_five_others): found_count += 1 # This is the part that I want to output on HTML page. report.write('{} part of document found in {} document. \n'.format( original_each_five, each_file)) else: pass else: pass -
Use python requests to login and upload a file on a django site. csrf token error
I have a django website where login in is required to upload a file. The file is part of a model form field. Both login (auth) and file upload work well when running straight from the browser. However when using python requests, only login works and upload fails with a crsf error. Below are code samples. forms.py class DatabaseUploadForm(forms.ModelForm): class Meta: model = Profile fields = ["dbfile"] upload.html <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Upload Database</legend> {{ p_form}} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Update</button> </div> </form> login_and_upload_script.py user = "user1" password="passwrd1" url_login='http://127.0.0.1:8000/users/login/' url_upload='http://127.0.0.1:8000/users/upload/' client = requests.session() client.get(url_login) csrftoken = client.cookies['csrftoken'] files={'dbfile':('files.db', open('file.db', 'rb'))} login_data = {'username':user,'password':password, 'csrfmiddlewaretoken':csrftoken, 'next': url_upload} r1=client.post(url_login,data=login_data) print(r1.status_code) print('\n=================================================================\nLogged In......\nConti') client.get(url_upload) csrftoken2 = client.cookies['csrftoken'] files={'dbfile':('MARKSDB.db', open('MARKSDB.db', 'rb')), 'csrfmiddlewaretoken':csrftoken2} r=requests.post(url_upload, files = files, headers=dict(Referer=url_upload)) print(r.status_code) print(r.text) print('\n=================================================================\nDone') The output 200 ================================================================= Logged In...... Continue 403 <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta name="robots" content="NONE,NOARCHIVE"> <title>403 Forbidden</title> <style type="text/css"> html * { padding:0; margin:0; } body * { padding:10px 20px; } body * * { padding:0; } body { font:small sans-serif; background:#eee; color:#000; } body>div { border-bottom:1px solid #ddd; } h1 { font-weight:normal; margin-bottom:.4em; } h1 span { font-size:60%; color:#666; font-weight:normal; … -
Django select a random image
I'm trying to select a random image from a given directory. I have found Random_Image on GitHub and I'm trying to use that. Here's a snippet of the instructions: Snippet of Instructions I'm relatively new to Django so this might seem like a silly question, but what am I doing wrong here? When I run the code below I get the following error: FileNotFoundError at / [WinError 3] The system cannot find the path specified: 'app_pickfeel/static/app_pickfeel/app_pickfeel/images/9.jpg' Random_Image.py import os import random from django import template from django.conf import settings # module-level variable register = template.Library() @register.simple_tag def random_image(image_dir): try: valid_extensions = settings.RANDOM_IMAGE_EXTENSIONS except AttributeError: valid_extensions = ['.jpg', '.jpeg', '.png', '.gif', ] if image_dir: rel_dir = image_dir else: rel_dir = settings.RANDOM_IMAGE_DIR rand_dir = os.path.join(settings.MEDIA_ROOT, rel_dir) files = [f for f in os.listdir(rand_dir) if os.path.splitext(f)[1] in valid_extensions] return os.path.join(rel_dir, random.choice(files)) Settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # template tags 'app_pickfeel.templatetags.random_Image' ] MEDIA_ROOT = 'app_pickfeel/static/app_pickfeel/' RANDOM_IMAGE_DIR = '/images/' RANDOM_IMAGE_EXTENSIONS = ['.jpg','.jpeg','.png','.gif'] MEDIA_URL = '/images/' img src <img src="{{ MEDIA_URL}}{% random_image "app_pickfeel/images/" %}"> Images are located in the directory: Pickfeel/app_pickfeel/static/aoo_pickfeel/images Any help would be greatly appreciated. -
How to use an object from outer scope in Django API handler
TL;DR: I run a Django server with a TCP socket connection. I need to inject the TCP connection instance to the REST api handlers, in order to make actions. I can't figure out HOW to share memory between the Django and my other code. I am working on a REST Django server. In urls.py i defined do_something api handler: urlpatterns = [ path('admin/', admin.site.urls), path('something/', do_something) ] in manage.py: To simplify, I used name instead of tcp_connection and its logic. name = None @api_view(["GET"]) def do_something(request): print("name", name) # prints None. Expected {"value": "lala"} return Response(None, status.HTTP_200_OK) def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings') global name name = { "value": "lala" } execute_from_command_line(sys.argv) if __name__ == '__main__': print(f'Initiating') main() Thoughts As I am new to python, that might be silly. It looks like it's running in another process and therefor no shared memory. If thats correct, how can i inject the object instance the handler needs? Thanks! -
Do not allow the user administrator without deleting in django
Good evening dear ... I am inexperienced in django, I wanted to have a way to prevent the admin user from deleting himself in the admin.py file, how should the code be to prevent this? I thank you in advance for your helpful attention. -
GraphQL Mutation in Graphene for Object with Foreign Key Relation
I'm building a simple CRUD interface with Python, GraphQL (graphene-django) and Django. The CREATE mutation for an Object (Ingredient) that includes Foreign Key relations to another Object (Category) won't work. I want to give GraphQL the id of the CategoryObject and not a whole category instance. Then in the backend it should draw the relation to the Category object. In the Django model the Ingredient Object contains an instance of the Foreign key Category Object (see code below). Is the whole Category Object needed here to draw the relation and to use Ingredient.objects.select_related('category').all()? The create mutation expects IngredientInput that includes all properties and an integer field for the foreign key relation. So the graphQL mutation itself currently works as I want it to. My question is similar if not the same as this one but these answers don't help me. models.py: class Category(models.Model): name = models.CharField(max_length=50, unique=True) notes = models.TextField() class Meta: verbose_name = u"Category" verbose_name_plural = u"Categories" ordering = ("id",) def __str__(self): return self.name class Ingredient(models.Model): name = models.CharField(max_length=100) notes = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE) class Meta: verbose_name = u"Ingredient" verbose_name_plural = u"Ingredients" ordering = ("id",) def __str__(self): return self.name schema.py: class CategoryType(DjangoObjectType): class Meta: model = Category … -
Does a Django Application that uses REST framework need a model?
I built an application that uses REST apis to inject information into a huge already existing database for a company. The application is a web form that the user fills out. My application then serializes the user's responses into a json that it uses to send post requests to the existent db. My Django app also is connected to a SQL Server db where it is saving the responses of the user into the fields that I created in my models.py. Is there a better way to do this? It seems like I'm saving all the information twice! A waste of space.