Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Starting a Django Docker project and getting error: ERROR: build path app/app either does not exist, is not accessible, or is not a valid URL
I'm using a Docker Django quick start tutorial. My dockerfile: FROM python:3.7.0-alpine WORKDIR /usr/src/app ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade pip COPY ./requirements.txt /usr/src/app/requirements.txt RUN pip install -r requirements.txt COPY . /usr/src/app/ My docker-compose: version: '3.7' services: web: build: ./app command: python manage.py runserver 0.0.0.0:8000 volumes: - ./app/:/usr/src/app/ ports: - 8000:8000 env_file: - ./.env.dev The problem When trying to run the following command: docker-compose build I receive the following error: ERROR: build path /Users/defaultuser/Documents/dev/simple_product_inventory/app/app either does not exist, is not accessible, or is not a valid URL. Could somebody point me in the right direction as to whats going wrong? -
Mix data and schema migrations in one migrations file (Django)?
I've heard the opinion that mix data migration and structure migrations is bad practice in Django. Even if you are specify atomic=False in your Migration class. But i could not find any information on this topic. Even my more expirience collegues could not answer this question. So, is it bad to mix data and structure migrations? If so why? What exactly may happen if i do it? -
Setting verbose name of function field in Django
I have a simple Model like this: class Artist(models.Model): class Meta: verbose_name = "Artist" verbose_name_plural = "Artists" name = models.CharField(max_length=128, unique=True, blank=False) def test_function(self): return 'xyz' And Admin: class ArtistAdmin(admin.ModelAdmin): list_display = ['name', 'test_function'] search_fields = ['name'] readonly_fields = [] Now in the list view, the function field is verbosed as test_function: In a normal field I would use the Field.verbose_name parameter. How do I achieve that with the function field? -
Import CSV file with django
1.Summarize the problem I am importing a csv file with django. Only the fist line seems to be imported in my database. Here is the code inside myview. views.py def upload_csv(request): chantiers = Chantier.objects.all() data = {} if "GET" == request.method: return render(request, "chantiers/upload_csv.html", data) # if not GET, then proceed try: csv_file = request.FILES["csv_file"] if not csv_file.name.endswith('.csv'): messages.error(request,'File is not CSV type') return HttpResponseRedirect(reverse("chantiers:upload_csv")) #if file is too large, return if csv_file.multiple_chunks(): messages.error(request,"Uploaded file is too big (%.2f MB)." % (csv_file.size/(1000*1000),)) return HttpResponseRedirect(reverse("chantiers:upload_csv")) file_data = csv_file.read().decode("utf-8") print("1") lines = file_data.split("\n") #loop over the lines and save them in db. If error , store as string and then display for line in lines: line = line.strip() if not line or line.startswith("#"): continue print(line) # following line may not be used, as line is a String, just access as an array #b = line.split() print(line[0]) fields = line.split(",") data_dict = {} data_dict["name"] = fields[0] data_dict["addresse"] = fields[1] data_dict["postcode"] = fields[2] data_dict["city"] = fields[3] print("3") try: form = ChantierForm(data_dict) if form.is_valid(): form.save() print("form saved") return render(request, 'chantiers/index_table.html', {'chantiers': chantiers}) else: print(form.errors.as_json()) logging.getLogger("error_logger").error(form.errors.as_json()) except Exception as e: print(e) logging.getLogger("error_logger").error(repr(e)) pass except Exception as e: print(e) logging.getLogger("error_logger").error("Unable to upload file. "+repr(e)) messages.error(request,"Unable to upload … -
Django Include ManyToManyField on "other" model in ModelForm
I would like to have a form with the preselected checkboxes of a ManyToManyField. models.py class Store(models.Model): ... class Brand(models.Model): stores = models.ManyToManyField(Store, blank=True, related_name="brands") forms.py class StoreForm(ModelForm): class Meta: model = Store fields = ('brands',) I get this exception: django.core.exceptions.FieldError: Unknown field(s) (brands) specified for Store How is it possible to include the ManyToMany field from "the other side" of the model (from Store)? -
Django 3.0 Admin Change Page Not Displaying Selected Option Correctly
I am running Django 3.0 and using Chrome Version 80.0.3987.132 (Official Build) (64-bit) and Firefox version 74 (64-bit). I have a select box on an admin change page for a model, and the correct value from the database is shown this way on the html source page generated by django: <option value="228">Frank</option> <option value="8" selected>Sam</option> <option value="19">Henry</option> However, the page is displayed in both browsers, Chrome and Firefox, with the default value "Pick one of the people", as if nothing has been selected. If I select another value from the drop down list, it is correctly inserted into the database, but the html on the admin change page still does not have selected="selected" in the correct option, but just the word 'selected' as shown above. I was looking online at the correct way to select an option in an option list, and it seems the correct (X)HTML way is to use selected="selected" in the option tag. Why is Django generating the old HTML way with just the word 'selected' in the option tag? Is there a way to fix this, or is this a bug in django or my browsers? I am not using any javascript or css on this … -
Django: redirect to view where login was called
I have a very common problem - after login I want to redirect to the page where login was called. I can describe situation exactly like here: Django: Redirect to previous page after login There are 2 options where you can log in - from the home page (which is defined in base.html) and from bokeh.html (other views inherit from bokeh) my base.html and bokeh.html have the same block to redirect to login. Difference is, that login called from home page should return to home page and from other page should return to page where was called. <li class="nav-item"> <a class="nav-link" href="{% url 'login' %}">Login</a> </li> my login.html <form method="POST"> {% csrf_token %} <div class="form-group"> <input type="text" class="form-control" placeholder="Enter Username" name="username" required> </div> <div class="form-group"> <input type="password" class="form-control" placeholder="Enter Password" name="password" required> </div> <div class="form-group"> <button type="submit" class="btn btn-dark">Login</button> </div> </form> and views.py def login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username,password=password) if user is not None: auth.login(request,user) return redirect('home') else: messages.info(request,'Invalid credentials') return redirect('login') else: return render(request,'login.html') I was trying to add next to my form in login.html but it didn't work. While accessing to login from page other than home page it … -
Swift 5 How to save UIImagePickerController edited image and upload to Django Rest Framework
Within my Swift app I am attempting to upload the selected image from UIImagePickerController to my Django Rest Framework backend. The problem: (Of many) Resource used: https://www.hackingwithswift.com/read/10/4/importing-photos-with-uiimagepickercontroller I have a "Change Image" button that brings up the image picker when the button is selected and the didFinishPickingMediaWithInfo handles generating the UUID for the photo's name, sets the image to the UIImageView on the storyboard and writes to the documents directory. However, I cannot upload the selected (now saved) image by its name or url. I've confirmed that I am able to upload images using Postman's form-data for Content-Type so I'm leaning more towards the Swift side being wrong. When printing to confirm paths: I receive the following imageName:::> testios1-a56078dc9bd749e98ebf095b94e9e3fc-606600911 jpegData:::> 1088255 bytes imagePath:::> file:///Users/testios1/Library/Developer/CoreSimulator/Devices/EE4E4C59-52FD-4ACB-9024-F2A3ACD3F794/data/Containers/Data/Application/E5BB861E-E3C9-47C7-8897-CD5535B259C6/Documents/testios1-a56078dc9bd749e98ebf095b94e9e3fc-606600911 imagePathExtension:::> imagePathAbsoluteURL:::> file:///Users/testios1/Library/Developer/CoreSimulator/Devices/EE4E4C59-52FD-4ACB-9024-F2A3ACD3F794/data/Containers/Data/Application/E5BB861E-E3C9-47C7-8897-CD5535B259C6/Documents/testios1-a56078dc9bd749e98ebf095b94e9e3fc-606600911 imagePathAbsoluteString:::> file:///Users/testios1/Library/Developer/CoreSimulator/Devices/EE4E4C59-52FD-4ACB-9024-F2A3ACD3F794/data/Containers/Data/Application/E5BB861E-E3C9-47C7-8897-CD5535B259C6/Documents/testios1-a56078dc9bd749e98ebf095b94e9e3fc-606600911 imagePathTestFileIsURL:::> true IBAction @IBAction func changeProfileImageButtonDidTouch(_ sender: Any) { let picker = UIImagePickerController() picker.allowsEditing = true picker.delegate = self picker.sourceType = .photoLibrary present(picker, animated: true, completion: nil) } didFinishPickingMediaWithInfo func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { // UserDefaults guard let username = UserDefaults.standard.string(forKey: "username") else { return } // Generate UUID var uuid = UUID().uuidString uuid = uuid.replacingOccurrences(of: "-", with: "") uuid = uuid.map { $0.lowercased() }.joined() // … -
DRF: How to get view to accept json with a list of dictionaries?
I'm using the APIClient to test my views. resp__1 = self.client.post(reverse('templates'), data=dict(data)) dict(data) shows the following: { "t_stops": [ { "address__pk": 1, "stop_num": 1 }, { "address__pk": 2, "stop_num": 2 } ], "customer__pk": 1 } What I don't want is for all my values in the JSON to be a list. Example would be my customer__pk value showing as [1]. When I do print(request.POST) in one of my views it shows the following: <QueryDict: {'t_stops': ["{'address__pk': 1, 'stop_num': 1}", "{'address__pk': 2, 'stop_num': 2}"], 'customer__pk': ['1']}> What's the proper way of getting these values to show correctly in Django rest? -
Django : How to build create view using forms and querysets?
I'm trying to create reservation create view that allows to break down the reservation process into 3 stages for handling all the database queries and displaying relevant choices accordingly to linkage between models (Personnel Profile has many to many key on Service) 1st stage - allows user to select service 2nd stage - displays available staff members (PersonnelProfile) who are handling this service 3rd stage - displays all the free dates / times based on staff member schedule / existing reservations, POST creates the reservation I got stuck at the 2nd stage as my form doesn't validate. I would appreciate any advise how to overcome this issue or how to handle the idea differently. Sorry for the long post :) Service class Service(models.Model): name = models.CharField(max_length=100) description = models.TextField() price = models.IntegerField() duration = models.IntegerField() def __str__(self): return self.name PersonnelProfile class PersonnelProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birth_date = models.DateField(default=None, null=True) address = models.CharField(max_length=200) services = models.ManyToManyField(Service) image = models.ImageField(default='profile_pics/default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.first_name} {self.user.last_name}' Schedule Model class Schedule(models.Model): user = models.OneToOneField(PersonnelProfile, on_delete=models.CASCADE) availability_days = models.ManyToManyField(WorkDay) start_hour = models.TimeField() end_hour = models.TimeField() def __str__(self): return f'Schedule of {self.user.user.first_name} {self.user.user.last_name}' WorkDay Model class WorkDay(models.Model): day_choices = [(str(i), calendar.day_name[i]) for i in … -
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: …