Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why calling method inside views.py after successful submission of forms doesn't clear the form?
Views.py def form_name_view(request): form = FormName() if request.method == "POST": form = FormName(request.POST) if form.is_valid(): form.save(commit=True) return HttpResponseRedirect('/') # return index(request) else: print('INVALID FORM INPUTS') return render(request, 'first_app/form_page.html', {'form': form}) When I use HttpResponseRedirect to get back to my index page, then everything works correct, but the concern is if I use calling index method instead of HttpResponseRedirect then the behavior is a little bit insane: After reaching index page if I hit refresh then alert appears says: The page that you're looking for used information that you entered. Returning to that page might cause any action you took to be repeated. Do you want to continue? If i want to get back to the same form page, by calling that same method again like return form_name_view(request) The new form is already filled with previous inserted data, with the message on the form Topic with this Topic name already exists. The question is what is the reason, calling method results like this? -
How to implement group by complex queries in django
1.UPDATE item_new JOIN (SELECT reporting_id,max(dotcom_asset_ksn) AS dksn FROM item_new GROUP BY reporting_id) b ON item_new.reporting_id = b.reporting_id SET item_new.dotcom_asset_ksn = b.dksn WHERE item_new.dotcom_asset_ksn is null and lower(bu_name)='footwear' 2.select ksn from event where event_type_id in(%s,%s) group by ksn having instr(group_concat(event_type_id),%s) > 0 and instr(group_concat(event_type_id),%s)=0 How to implement this query in django. Can anyone help me??? -
Create an universal function and abstract class for multiple apps
So I create some abstract classes in Django to override in for Model like this: import uuid from django.db import models class Identifier: @staticmethod def hex(): return uuid.uuid4().hex class Model(models.Model): class Meta: abstract = True id = models.CharField( max_length=32, unique=True, primary_key=True, default=Identifier.hex, editable=False, verbose_name='Identifier', ) created = models.DateTimeField( auto_now_add=True ) modified = models.DateTimeField( auto_now=True ) I have multiple apps at least 3 apps in my project. Should I created another app called abstracts to put every abstract classes and universal function or I put them inside the project level folder? -
Django 'WSGIRequest' object has no attribute 'data'
I am trying to do a post request to a API, and save the result into one of my database table. This is my code. This is my model. patientId is a foreign key to the userId of MyUser table class MyUser(AbstractUser): userId = models.AutoField(primary_key=True) gender = models.CharField(max_length=6, blank=True, null=True) nric = models.CharField(max_length=9, blank=True, null=True) birthday = models.DateField(blank=True, null=True) birthTime = models.TimeField(blank=True, null=True) class BookAppt(models.Model): clinicId = models.CharField(max_length=20) patientId = models.ForeignKey(MyUser, on_delete=models.CASCADE) scheduleTime = models.DateTimeField(blank=True, null=True) ticketNo = models.CharField(max_length=5) status = models.CharField(max_length=20) view.py . The api url is from another django project @csrf_exempt def my_django_view(request): if request.method == 'POST': r = requests.post('http://127.0.0.1:8000/api/makeapp/', data=request.POST) else: r = requests.get('http://127.0.0.1:8000/api/makeapp/', data=request.GET) if r.status_code == 201 and request.method == 'POST': data = r.json() print(data) patient = request.data['patientId'] patientId = MyUser.objects.get(id=patient) saveget_attrs = { "patientId": patientId, "clinicId": data["clinicId"], "scheduleTime": data["created"], "ticketNo": data["ticketNo"], "status": data["status"], } saving = BookAppt.objects.create(**saveget_attrs) return HttpResponse(r.text) elif r.status_code == 200: # GET response return HttpResponse(r.json()) else: return HttpResponse(r.text) the result in the print(data) is this. [31/Jan/2018 10:21:42] "POST /api/makeapp/ HTTP/1.1" 201 139 {'id': 22, 'patientId': 4, 'clinicId': '1', 'date': '2018-07-10', 'time': '08:00 AM', 'created': '2018-01-31 01:21:42', 'ticketNo': 1, 'status': 'Booked'} But the error is here File "C:\Django project\AppImmuneMe2\customuser\views.py", line 31, in … -
Django urls help - not able to access view
Let me start by saying I'm new to Django and I realize this seems simple (and I'm hoping it is). I'm following a tutorial that is taking me through the basic set up of a simple Django site, and I've found myself stuck at a point where I'm simply calling on a new view the tutorial just had me add. (for those interested, the tutorial is here https://overiq.com/django/1.10/views-and-urlconfs-in-django/) So, I've got my server up and running, and I'm trying to access http://127.0.0.1:8000/blog/time/ When I try to access that view, I get the error: Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: ^blog ^time/$ [name='todays_time'] ^blog ^$ [name='blog_index'] ^admin/ The current path, blog/time/, didn't match any of these. Here is the layout of my Django project: My mysite's urls.py file looks like this: from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^blog/', include('blog.urls')), url(r'^admin/', admin.site.urls), ] My blog package's urls.py file looks like this: from django.conf.urls import url from blog import views urlpatterns = [ url(r'^time/$', views.today_is, name='todays_time'), url(r'^$', views.index, name='blog_index'), ] my blog package's views.py looks like this: from django.http import HttpResponse import datetime def index(request): return HttpResponse("Hello Django!!!") def … -
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 4: ordinal not in range(128)
I'm facing some trouble with Unicode. I'm a beginner in programming, so I couldn't understand the other answers related to this issue here. TraceBack Traceback: File "/usr/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/django/django_project/learn/views.py" in index 19. if str(get_one_phrasalverb) not in cannot_be_random: Exception Type: UnicodeEncodeError at /learn/keep-from/ Exception Value: 'ascii' codec can't encode character u'\xa0' in position 4: ordinal not in range(128) Problematic code part cannot_be_random = request.session.get('cannot_be_random') if str(get_one_phrasalverb) not in cannot_be_random: cannot_be_random.append(str(get_one_phrasalverb)) request.session['cannot_be_random'] = cannot_be_random Please tell me if some part of the code or part of the traceback is missing. Could someone help me, please? -
DJango FileSystem .url reading from wrong location
I have a form containing an ImageField and a FileField The files are uploading to the correct folders, however when I try to retrieve the url to display on screen it gives me an incorrect location fs_img = FileSystemStorage(location='media/images/') imageName = fs_img.save(image.name,image) uploaded_image_url = fs_img.url(imageName) E.G. Images upload as media/images/profile_image.jpg However when I try to retrieve the url of the file that just saved, in order to save the location to a DB, it retrieves it as media/profile_image.jpg which doesn't exist I am aware that the default location used by FileSystemStorage is MEDIA_ROOT and that seems to be just what fs_img.url(imageName) is using where BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Also, I have found that in the models.py file using an upload_to setting has no effect image = models.ImageField( upload_to = 'media/images/', default='media/no_image.png' ) How do I get fs_img.url(imageName) to return the correct URL so that I can save it to my database? -
Views/Templates returning incorrect information in Django
I have a view which is returning all products, not just filtered ones. Even if I removed the last line products =, the template still renders all database objects. class ProductListView(ListView): context_object_name = 'products' model = models.Product template_name = "catalogue/catalogue.html" products = Product.objects.filter(category__name="sundries") This is my template logic: {% for product in products %} <tr> <td><h5>{{ product.name }}</h5> <p>Cooked with chicken and mutton cumin spices</p></td> <td><p><strong>£ {{ product.price }}</strong></p></td> <td class="options"><a href="#0"><i class="icon_plus_alt2"></i></a></td> </tr> {% endfor %} and Models.py lass Category(models.Model): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, unique=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name # def get_absolute_url(self): # return reverse('shop:product_list_by_category', args=[self.slug]) class Product(models.Model): category = models.ForeignKey(Category, related_name='products') name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ('-created',) index_together = (('id', 'slug'),) def __str__(self): return self.name # def get_absolute_url(self): # return reverse('shop:product_detail', args=[self.id, self.slug]) -
Format to JSON data from multiple Select
I already had read a lot but I can't find a solution for this. I have this model: class Seller(models.Model): bc_seller_id = models.IntegerField('Seller ID (in BigCommerce)', choices=get_bigcommerce_ids()) seller_customers = models.TextField('Associated Customers', choices=get_bigcommerce_ids(True)) last_update = models.DateTimeField(auto_now=True) I want to store seller_customers as a JSON string in the database. I got the information from a API request so I only need to store the ID's, nothing more. In my form I have: class Meta: model = Seller exclude = () widgets = { 'seller_customers': Select2MultipleWidget(), } The admin form renders OK, but when I try to save display this error: Select a valid choice. [8] is not one of the available choices. Even if by: class CustomersForm(forms.ModelForm): def __init__(self, *args, **kwargs): I change the value of the data, it's rendered as ["new value"] with the "[]". I suppose that the system is trying to validate the value with the option value witch is an integer and offcourse [8] o [8, 5] isn't. What is the right thing to do to use a Multiple Select and store the data as JSON in the database. I'm using MySQL, Django 2.0, Python 3.x -
Django-mptt different order based on level
I'm trying to make a threaded commenting system based on django-mptt. The problem that I'm having is that the order of the comments cannot be changed according to their level. What I am trying to achieve is a system in which "first level comments" are in ascending order based on submission date , while "nth level comments" (i.e. replies) are ordered in the opposite direction (check for example the youtube commenting system). I have the order of insertion defined like this: "class MPTTMeta: order_insertion_by=['-submit_date']" and the recursetree templatetag to render the tree with the comments. Is there any solution to set the order of insertion (or display) based on the level of each comment? Thanks -
IntegrityError using fixtures with Django 1.11 TestCase
I'm writing a test in Django 1.11 and trying to load some fixture data into my local sqlite database (retrieved from the real database via manage.py dumpdata) like so: class MyTest(TestCase): fixtures = [os.path.join(settings.BASE_DIR, 'myapp', 'tests', 'fixtures.json')] Part of the fixture data is User models where we have a custom User with a different USERNAME_FIELD, so all of the username fields on each of our records is blank. However, when I try and run my test using my fixture, I get the following error: IntegrityError: Problem installing fixture '.../fixtures.json': Could not load myapp.CustomUser(pk=41): column username is not unique pk 41 is the second CustomUser record in my fixtures.json. How can I tell Django's testing framework to ignore the constraint it thinks it needs to enforce, or otherwise get my fixture data loaded for testing? -
How to escape symbols entered in django admin to html representation
I have a model that has a regular text field, that needs to be able to accept user pasted text data into it which may contain scientific symbols, specifically lowercase delta δ. The users will be entering the data through the model admin. I'm using a mysql backend, and the encoding is set to Latin-1. Changing the DB encoding is not an option for me. what i would like to do, for simplicity's sake, is have the admin form scrub the input text, much like sanitation or validation, but to escape the characters such as δ to their HTML representation,so that i can store them in the DB without having to convert to Unicode and then back again. What utilities are available to do this? I've looked at escape() and conditional_escape(), but they do not seem to do what i want them to (not escape the special characters) and the django.utils.encoding.force_text() will encode everything, but my data will render as its Unicode representation if i do that. The site runs on django 1.10 and python 2.7.x any help or thoughts are much appreciated. -
CreateView with ListView in django init form
Im working with sigurdga/django-jquery-file-upload for multiple upload images, so i want to achieve that when the user enter a page, the photos uploaded by him appears in the page so, is there a way no initialize a django CreateView with all the objects displayed like a ListView? I have this createview. class PictureCreateView(CreateView): model = Picture fields = "__all__" template_name = 'fileupload/picture_form.html' # form_class = PictureForm # def get_initial(self): # initial = super(PictureCreateView, self).get_initial() # initial = initial.copy() # files = [serialize(p) for p in self.get_queryset()] # data = {'files': files} # response = JSONResponse(data, mimetype=response_mimetype(self.request)) # response['Content-Disposition'] = 'inline; filename=files.json' # return response def form_valid(self, form): self.object = form.save(commit=False) self.object.usuario_id = self.request.user.id self.object.save() usuario = User.objects.get(id=self.request.user.id) if usuario: photos = Picture.objects.filter(usuario_id=usuario.id) for photo in photos: photo.usuario_id = self.request.user.id photo.save() files = [serialize(self.object)] data = {'files': files} response = JSONResponse(data, mimetype=response_mimetype(self.request)) response['Content-Disposition'] = 'inline; filename=files.json' return response def form_invalid(self, form): data = json.dumps(form.errors) return HttpResponse(content=data, status=400, content_type='application/json') ListView class PictureListView(ListView): model = Picture template_name = 'fileupload/picture_list.html' Html {% extends "fileupload/upload_base.html" %} {% block content %} <ul> {% for picture in object_list %} <img src="/media/{{ picture.file }}" /> {% endfor %} </ul> {% endblock %} -
Django Filter Not Returning Right Results
I have a view where I am trying to filter a product by category. class ProductListView(ListView): context_object_name = 'products' model = models.Product template_name = "catalogue/catalogue.html" products = Product.objects.all() birdish = Product.objects.filter(category="Biryani Dishes") So I have a category called 'Biryani Dishes'. I get the error ValueError: invalid literal for int() with base 10: 'Biryani Dishes' If I change the query to (name='Chicken Biryani') I get back all the products. (I am expecting just Chicken Biryani). Ideally, I would like to create a generic query that takes in the category as an argument and I can specify the actual name on the HTML template. Any help is really appreciated. -
What are the ways for creating a Django project structure
I have been following Django tutorials. It says I can create projects using the following command: django-admin startproject mysite And then I can create apps using python manage.py startapp polls This gives me a standard project structure. When creating real life websites/portal is this how project structures are? Are there other ways of creating projects? -
What is the most efficient way to count votes on an object?
I want to count votes on model object. I am thinking there are two ways to accomplish this: Approach 1 class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) vote_count = models.IntegerField() And then get the model, update the count, then re-save the model. Or: Approach 2 class Vote(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) votes = models.ManyToManyField(Vote,related_name='questions') In this way I can add to the votes and then count on all votes when I need a summary. Which approach is most efficient from a database cost perspective as well as future scalability? -
rest framework's list_route returns empty
I am using django rest framework. I have a ViewSet similar to as defined below class ModelViewSet(viewsets.ModelViewSet): queryset = Model.objects.all() serializer_class = ModelSerializer @list_route(url_name="custom") def custom(self, request): objects = Model.objects.all() serializer = self.get_serializer(objects) return HttpResponse("{} </br> {}: ".format(objects, serializer)) When I go to the custom url for the list_route I get ,,,,,]> ModelSerializer(,,,,,]>, context = ...) however when I got to the base url, I can see the full list of all my model's objects. I am confused cause it seems to me it should be using the same data. It seems that there are the correct number of objects in the list (based on the number of commas), however the objects are unpopulated. Following the Django rest guide, it suggests to use serializer.data, however since my objects are not there this produces an error. Any ideas? -
Restart celery beat and worker during Django deployment
I am using celery==4.1.0 and django-celery-beat==1.1.0. I am running gunicorn + celery + rabbitmq with Django. This is my config for creating beat and worker celery -A myproject beat -l info -f /var/log/celery/celery.log --detach celery -A myproject worker -l info -f /var/log/celery/celery.log --detach During Django deployment I am doing following: rm -f celerybeat.pid rm -f celeryd.pid celery -A myproject beat -l info -f /var/log/celery/celery.log --detach celery -A myproject worker -l info -f /var/log/celery/celery.log --detach service nginx restart service gunicorn stop sleep 1 service gunicorn start I want to restart both celery beat and worker and it seems that this logic works. But I noticed that celery starts to use more and more memory during deployment and after several deployments I hit 100% memory use. I tried different server setups and it seems that it is not related. -
Render objects using CreateView init, Django
I want to do render all the registers from an object using CreateView, i know how to do it with normal view but not with CreateView. model Picture class Picture(models.Model): usuario = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, related_name="pictures_usuario") # session = models.ForeignKey(Session, null=True, blank=True) file = models.ImageField(upload_to="pictures") slug = models.SlugField(max_length=50, blank=True) def __str__(self): return self.file.name @models.permalink def get_absolute_url(self): return ('upload-new', ) def save(self, *args, **kwargs): self.slug = self.file.name super(Picture, self).save(*args, **kwargs) def delete(self, *args, **kwargs): """delete -- Remove to leave file.""" self.file.delete(False) super(Picture, self).delete(*args, **kwargs) view.py from Leankd_app.fileupload.models import Picture def testFormu(request): p = Picture.objects.all() return render(request, 'test/formu.html', {'p': p}) template.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% for photos in p %} {{ photos.id }} <br> {{ photos.slug }} <br> {{ photos.file }} {% endfor %} </body> </html> How can achive the same using CreateView? I have this files. CreateView en views.py class PictureCreateView(CreateView): # model = Picture # fields = "all" form_class = PictureForm template_name = 'fileupload/picture_form.html' def get_initial(self): initial = super(PictureCreateView, self).get_initial() initial = initial.copy() p = Picture.objects.all() self.initial = {"p": p} return initial def form_valid(self, form): self.object = form.save(commit=False) self.object.usuario_id = self.request.user.id self.object.save() usuario = User.objects.get(id=self.request.user.id) if usuario: photos = … -
Use external data in Django
How can I list external Json data get from mongodb into Django page? The Json data has table structure. Django is should just read this data not require create, update and delete actions. How can I do this? -
Pass a initial object from CreateView to Django Template
I´m working with 3d party django-jquery-file-upload to upload multiple images, there i have these 2 urls to render de templates url(r'^$', PictureCreateView.as_view(), name='upload-new'), url(r'^delete/(?P<pk>\d+)$', PictureDeleteView.as_view(), name='upload-delete'), What i want to do is that when i call PictureCreateView get initialize with the photos from the user, so i need to get all those photos from the createview but when i render it to the template any happen. CreateView class PictureCreateView(CreateView): # model = Picture # fields = "__all__" form_class = PictureForm template_name = 'fileupload/picture_form.html' def get_initial(self): initial = super(PictureCreateView, self).get_initial() initial = initial.copy() p = Picture.objects.filter(usuario_id=3) self.initial = {"p": p} return initial def form_valid(self, form): self.object = form.save(commit=False) self.object.usuario_id = self.request.user.id self.object.save() usuario = User.objects.get(id=self.request.user.id) if usuario: photos = Picture.objects.filter(usuario_id=usuario.id) for photo in photos: photo.usuario_id = self.request.user.id photo.save() files = [serialize(self.object)] data = {'files': files} response = JSONResponse(data, mimetype=response_mimetype(self.request)) response['Content-Disposition'] = 'inline; filename=files.json' return response def form_invalid(self, form): data = json.dumps(form.errors) return HttpResponse(content=data, status=400, content_type='application/json') class PictureForm(forms.ModelForm): class Meta: model = Picture exclude = ('slug', 'file', 'usuario') def __init__(self, *args, **kwargs): super(PictureForm, self).__init__(*args, **kwargs) picture = Picture.objects.get(usuario_id=3) self.fields['slug'] = picture.slug picture_form.html {% block content %} {{ form }} {%endblock %} i know im not using the self.initial = {"p": p} in … -
Every time I logout & log back in a new cart is created, Django Cart App
I'm new to Django! I'm trying to let unauthenticated user add products to cart. And when the login & refresh the card is associated with user. But the problem is for authenticated users. When authenticated user logs out and logs back in, a new cart is created for him. This is my function, it checks if I need to make a new cart or get the existing one. def new_or_get(self, request): cart_id = request.session.get("cart_id", None) qs = self.get_queryset().filter(id=cart_id) if qs.count() == 1: new_obj = False cart_obj = qs.first() if request.user.is_authenticated() and cart_obj.user is None: cart_obj.user = request.user cart_obj.save() else: cart_obj = Cart.objects.new(user=request.user) new_obj = True request.session['cart_id'] = cart_obj.id return cart_obj, new_obj -
i want to display only selected year data in Django
Here i put my code file so you can get idea about my code In my index.html {% load tag %} <body> <select name="select_year"> <option>2017</option> <option>2018</option> <option>2019</option> <option>2020</option> </select> </br> </br> <table border="1"> <tr> <td>No</td> <td>Name</td> <td>DOB</td> <td>Year</td> </tr> {% for Manvi_User in ordering %} <tr> <td>{{forloop.counter}}</td> <td>{{ Manvi_User.first_name }}</td> <td>{{ Manvi_User.dob}}</td> <td>{{year|calculate_year:forloop.counter0}}</td> </tr> {% endfor %} </table> </body> in vies.py def index(request): all_user = Manvi_User.objects.all() ordering = all_user.order_by('dob') return render(request, 'index.html', {'ordering': ordering}) in tag.py @register.filter def calculate_year(year, loop_counter): try: year = int(2017) except ValueError: return None else: return str(year + (loop_counter // 2)) in year i put static year using tag.py if user select 2019 i want to display only data who have year 2019 -
How to filter based on a nested Django JSONField
I have a json field for a model in my Django app that typically has nested json in it. I read that to filter on a JSONfield, you would use contains on the filter for whatever value you are looking for, but I'm not getting any results back even though I know the value does exist in the JSONField. Is there an extra step I need to use for nested json in a json field ? JSON Field "Field name is Content " "content": { "documents": [ { "id": "378", "name": "Test.pdf", "mediaFile": "http://localhost:8000/media/file.pdf" } ] } Query document_modules = WMDocumentModule.objects.filter(content__documents__contains={'id': "378"}) >>> document_modules: <QuerySet []> -
InMemoryUploadFile processing
I have a question about Django InMemoryUploadedFile processing. I tried to upload a simple csv file whose content is as below username,name user1,user1 I use the snippet below to get the file data and save it locally (Django REST framework) def put(self, request, filename, format=None): file_obj = request.data['file'] path = default_storage.save('demo.csv',ContentFile(file_obj.read())) However, the result file has content: ------WebKitFormBoundaryJaXsjE9oec2QW6jz Content-Disposition: form-data; name="demo.csv"; filename="demo.csv" Content-Type: text/csv username,user user1,user ------WebKitFormBoundaryJaXsjE9oec2QW6jz-- Is there any way that I can retrieve the csv file data only without the header and footer above? My purpose is to read the csv file, is there a way to read data directly without saving first? Thank you.