Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ORM: How to find all instances with unique names which has the lowest value?
I've got queryset with 50+ instances: products = Product.objects.filter(...).order_by['price'] Product model has: store = models.ForeignKey('Store',...) Each store has 10 products in the current queryset and there are 5 different stores in total. I'm trying to get one product from each store with a minimum price -
How do I correctly import my auth class
I created my own auth 'AuthOnPostOnly, but I am having trouble correctly importing it. note: I created an app called 'api'. also left out init.py from all directories in this example but they are all there. settings.py INSTALLED_APPS = [ 'pipeline.apps.PipelineConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # for testing 'django_nose', # thirdparty app 'bootstrap3', 'crispy_forms', 'bootstrap_pagination', 'mobilereports', 'rest_framework', 'api' ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'api.permissions.AuthOnPostOnly', ) } directory structure /proj /api urls.py views.py serializers.py /permissions permissions.py /proj /settings.py /urls.py error: Could not import 'api.permissions.AuthOnPostOnly' for API setting 'DEFAULT_PERMISSION_CLASSES'. AttributeError: module 'api.permissions' has no attribute 'AuthOnPostOnly' -
Dynamically add image to django page via javascript?
I'm trying to add an image to a django page via Mapbox's API, which has the following syntax: new mapboxgl.Popup() .setLngLat(features[0].geometry.coordinates) .setHTML(" <img src=\"../images/location_icon.png\" />") .addTo(map); Unfortunately, that doesn't seem to work. I assume that because we're skirting around the whole idea of templates (by dynamically adding the image), I don't need to use {% %} , but I'm not entirely sure about that. I've tried this as well, but to no avail: .setHTML(" <img src='{%\"images/location_icon.png\"%}' />") Does anybody know what the proper syntax is for accomplishing this? -
Annotate many to many with initial model django
I have these two models class Word(Model): word = CharField() categories = ManyToManyField('Category') class Category(Model): name = CharField() What I want to do is to output number of words for each set of categories: General (3 words) General, IT (7 words) Medicine (1 word) Archaic Words, IT (10 words) This means, that, for example, there are 3 words, that have only one category, namely General. What is the way to accomplish it in the smallest possible number of queries? First step is to fetch all possible sets, I use PostgreSQL: all_sets = Word.objects.annotate(category_names=ArrayAgg('categories__name')).values_list('category_names', flat=True).distinct() What next? I can, of course, fetch the number of words for every set: for category_set in all_sets: queryset = Word.objects.annotate(n=Count('categories')).filter(n=len(category_set)) for cat in category_set: queryset = queryset.filter(categories__name=cat) But I will hit the database for the every set of categories. Can this be improved? -
Django CountryField COUNTRIES_OVERRIDE & COUNTRIES_FIRST -- NOT WORKING
CountryField is working, but "United States of America" is too long, I prefer just "United States" or even "USA". Also, I want USA & GB at the top of the list when you pull down the pull down. When I first implemented COUNTRIES_OVERRIDE & COUNTRIES_FIRST, they were working. Then suddenly they stopped working, and have not worked since. I have been pulling my hair out! (Not literally.) In the models.py file where I import CountryField, I also import settings from django_countries.conf. Below the import lines, and above the model defintion that uses CountryField, I have these lines: settings.COUNTRIES_FIRST = [ 'US', 'GB' ] settings.COUNTRIES_OVERRIDE = { 'US': 'USA' } Troubleshooting tips would be appreciated. -
In the Django REST framework, how to allow partial updates when using a ModeViewSet?
I'd like to create a REST API for an object which can be partially updated. On http://www.django-rest-framework.org/api-guide/serializers/#partial-updates and example is given in which partial=True is passed when instantiating the serializer: # Update `comment` with partial data serializer = CommentSerializer(comment, data={'content': u'foo bar'}, partial=True) In my case, however, the model (which is called SessionType) has the following viewset: class SessionTypeViewSet(viewsets.ModelViewSet): queryset = SessionType.objects.all() serializer_class = SessionTypeSerializer where the serializer is defined as class SessionTypeSerializer(serializers.ModelSerializer): class Meta: model = SessionType fields = ('title',) How can I adapt the serializer in this use case so that partial is always True? -
Django Forms, how to validate form with startswith
I am trying to work out how to get the following bit of code working so that everything that starts with the tuple is valid, e.g. if the postcode 'GU15 56L' is entered it permits the postcode. Currently only the GU15 part is working (for this example). Something like start with but not sure where to start. class PostCodeForm (forms.Form): pcode = forms.CharField() def clean_pcode(self): permitted = {'GU15','GF34','FG34','BT25'} pcode = self.cleaned_data['pcode'].lower() if not pcode in (permitted): raise forms.ValidationError("Apologies, but does not currently deliver to you postcode.") return pcode Thanks for your help in advance -
Best approach to using unittest with Django
This may seem a very general question, but I hope not. I need to write tests for a Django backend before writing the Django code and then testing it. One of the first problems I can see is that this might use a lot of resources and be extremely slow. What is the standard way to test Django code? Do people write code snippets and test them individually before incorporating them into the whole or is there a better way or better framework than unittest? Is there a Django specific testing framework? Before you answer, I don't have much experience with Django, but I can learn if you point me to the right tutorials. Put simply, what is the best way to test Django code? -
django HTTP 405 Method Not Allowed in html form
I am new to Django and I've been trying to develop a simple site that asks the user for their email address and height. It then saves it in the database and sends an email to the user and redirects them to a page saying that it was successful. Now the problem is whenever I press 'Submit', I get a HTTP 405 method not allowed error. # urls.py urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), #url(r'^success/$', views.SuccessView.as_view(), name='success'), ] # forms.py class HeightForm(forms.ModelForm): class Meta: model = Height fields = ['email', 'height'] # views.py class IndexView(generic.ListView): form_class = HeightForm template_name = 'heights/index.html' def get_queryset(self): return Height.objects.all() class HeightFormView(View): form_class = HeightForm template_name = 'heights/success.html' def get(self, request): form = form_class(None) def post(self, request): print('a' * 1000) form = form_class(request.POST) if form.is_valid: email = form.cleaned_data['email'] height = form.cleaned_data['height'] form.save() return HttpResponseRedirect(template_name) #render(request, template_name, {'form': form}) # index.html {% extends 'heights/base.html' %} {% block body %} <h1>Collecting Heights</h1> <h3>Please fill the entries to get population statistics on height</h3> <form action="" method="post"> {% csrf_token %} <input type="email" name="email" placeholder="Enter your email address" required="true"/><br /> <input type="number" min="50" max="300" name="height" placeholder="Enter your height in cm" required="true" /><br /><br /> <input type="submit" name="submit" /> </form> <a … -
Different ways of calling render() in Django
I am having some difficulty understanding how render() works. I have read posts about the functionality of the function, however still have unanswered questions. Reading about it in the Django Docs, and looking at the source, it is not a method pertaining to any class. Instead, it is a function just like many others, and one that takes several arguments (request, template_name, etc). Though, in the Django Book, it is stated as a method you can call on a template object. That is, you can instantiate an object, and immediately call the render method on that object with some context. I have previously used it without specifying any template name, merely calling it on a template object with some context, as previously described. Why do the Docs describe it as a free-standing function, not belonging to a class, when it can be called on a template object like as if it was a method of a template class? Why don't I find a template class anywhere? What am I missing? -
How do I access my virtual environment when I go into Terminal (Mac)?
I was going through a tutorial on Django for the first time and had to restart my computer. After it restarted, I lost access to my virtualenv instance in terminal. Can anyone help get me back in? I can see the virtual environment. screenshot of Mac Terminal Location of virtual server on Mac -
Packaging Django code for deployment
I'm getting ready to move my Django project from my laptop to my server. What is the recommended way to do this? E.g., is there a Django command that will package everything up (and select the correct settings file for test vs prod servers) and create a zip or tar file that can be moved over to the server? Sort of like Ant for building Java projects. -
Django many to many relation not saving
Using Django 2.0.1 and PostgreSQL 9.2.18 I'm writing a simple photogallery application. In it I have a photo object and PhotoTag object. The photo can have many tags and the tags can be associated with many photos, thus it needing to be a ManyToManyField. Upon save of the submitted photo, a post_save receiver calls functions to make thumbnails (which work fine) and a function to update tags. The photo gets saved fine, update_tags gets called fine, tags get read from the photo fine, tags get saved into PhotoTag fine. But the manytomany table tying the two together does not get the new rows inserted. Unless the code exits abnormally during either the update_tags function or the post_save receiver function, thumbs after update_tags is called. I've even tried using a connection.cursor to write directly into the m2m table and it has the same behavior. If I try to call save() on the Photo object again, I just get into an infinite loop due to the post_save signal. I'm baffled as to what is going on. Any clues? -------------- From models.py -------------- def update_tags(instance): tags = get_tags(instance.image) # Set initial values pt = [] tagid = '' photoid = instance.id # Loop … -
Execute validate_unique when form doesn't include all fields
I recently had a situation where the validate_unique method from my model wasn't running. This is because one of the fields involved in the unique test wasn't included in the form. I tried many things in the form and the view before landing on this solution: I first injected the field into the object of the UpdateView, then ran the test in the Form in _post_clean. models.py class Link(ModelBase): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=200,blank=True,null=False) url = models.URLField(max_length=400,blank=False,null=False) profile = models.ForeignKey('Profile',null=False,blank=False,on_delete=models.CASCADE) class Meta: unique_together = ('url','profile') class Admin: pass forms.py class LinkForm(ModelForm): def _post_clean(self): ''' Be sure that the instance validate_unique test is run including the profile field ''' super(LinkForm,self)._post_clean() try: self.instance.validate_unique(exclude=None) except ValidationError as e: self._update_errors(e) class Meta: model = Link fields = ['title','url'] views.py class LinkUpdateView(UpdateView): model = Link form_class = LinkForm def get_form_kwargs(self): ''' Add profile to self.object before kwargs are populated ''' if hasattr(self, 'object') and self.object and self.profile: self.object.profile = profile kwargs = super(LinkUpdateView, self).get_form_kwargs() return kwargs Is there a better way to do this that doesn't involve overriding an internal function? -
Django knowledge requirement in python
it's about a month I am handling with python and what I know is its fundamental and OOP concepts and a little tkinter and other languages also css and html. My question is :what do I need to be prepared for django framework tutorial learning? -
Django ORM queries. How to conver sql to ORM
I have the following sql statement and I want to refactor it to ORM but don't know how left join works when we have no foreign keys between two tables. It basically checks table sag_diff for new businessLines. It insert only new ones to table BusinessLines. INSERT INTO tbl_BusinessLines ( BusinessLine_Name, Run_Date ) SELECT DISTINCT tbl_SAG_Diff.BUSINESS_LINE, tbl_SAG_Diff.Run_Date FROM tbl_SAG_Diff LEFT JOIN tbl_BusinessLines ON tbl_SAG_Diff.BUSINESS_LINE = tbl_BusinessLines.BusinessLine_Name WHERE((tbl_BusinessLines.BusinessLine_Name)IS null); here are my models: class BusinessLines(models.Model): BusinessLine_ID=models.IntegerField(primary_key=True) BusinessLine_Name=models.CharField(max_length=100, null=True) run_date = models.DateField(null=True) class SAG_diff(models.Model): Business_Line = models.CharField(max_length=255,null=True) RUN_DATE = models.DateField(null=True) -
django serialize a model in desired way for api
I have a model Staff which consists simple staff information. And I have another model Schedule with schedule information class Schedule(models.Model): staff = models.ForeignKey(Staff, models.SET_NULL, blank=True, null=True) attendance = models.DateTimeField() I am getting the schedule by date something like schedules = Schedule.objects.filter(attendance__date=today) Now I want to return json of it for the api. Currently I am doing raw_data = serializers.serialize("python", schedules) return JsonResponse(raw_data, safe=False) It is giving me response something like: ` [ { model: "schedule.schedule", pk: 11, fields: { staff: 1, attendance: "some_date", } } ] ` But I want the json to be without model name and instead of ID on foreign key I want user information and id instead of foreign key. ` [ { id: 11, fields: { staff: { id: 6, name: 'Jack' }, attendance: 'some_date', } } ] ` Can I get this from serializer of I have to make a custom dictionary and add all the field in my design and dump it ? Help will be much appriciated :) -
Postgres: Password authentication failed for user "user". Role "user" does not exists
I'm using Django created with the template cookie-cutter. When i try to run the project with docker locally it gives me the following error. FATAL: password authentication failed for user "user" DETAIL: Role "user" does not exist. But the role "user" exists. Using the comand postgres=# \du gives me the role "user" I have a .env file with the recommended configuration by cookie cutter. POSTGRES_PASSWORD=password POSTGRES_USER=user I tried giving the user a password and granting all privileges of the database to the user but doesn't works. -
Django 1.11 KeyError at /admin/login/ - Exception Value:'created'
In the console I can create a superuser, but when I try to log in to the admin panel I get the following Error Message I can post the traceback if needed. -
proper way to combine a field outside of my model in a pre-existing database
I am working with a pre-existing database called Employee. I have three separate fields i'd like to combine into a single field, but I can't add an additional field to the pre-exisiting database. I know the proper way to combine multiple fields into one field using python is '%s - %s %s' % (self.username, self.firstname, self.lastname) However, I can't call self outside the model, or at least i'm not sure where I would call self. My end goal is to have a select box with the combined field a user can search either first, last, or account name. My current model looks like the following: class Employee(models.Model): staff_id = models.IntegerField(db_column = 'Employee_ID') status_id = models.IntegerField(db_column = 'StatusID') username = models.CharField(db_column = 'SamAccountName',primary_key = True, max_length = 31) lastname = models.CharField(db_column = 'Surname', max_length = 63) firstname = models.CharField(db_column = 'GivenName', max_length = 63) title = models.CharField(db_column = 'Title', max_length = 127) class Meta: managed = False db_table = '[Employee]' I tried to add to my model, but when I call full_username it says the field doesn't exists, which is true because there isn't a field in the database. We aren't allowed to add a new field to the database. def … -
How to create multiple objects in DRF ignoring errors if object already exists?
I have a POST endpoint that accepts a JSON payload - parses values from it, creates dictionaries from those values - then feeds those dictionaries to model serializers to create objects. I don't believe DRF is meant for what I'm trying to do here, but it is a requirement. My main question using the example below is this: Currently if an instance exists, Django will throw an error about unique_constraint field error (exactly as it should). However, since this is kind of a weird endpoint, I need those errors ignored. So if for example a product already exists, instead of unique_constraint error, it just continues on and creates platform. The rest of this app will require that error to be thrown, it is only in this function that I wish to ignore those errors. Serializers are shared throughout the app so I don't really want to touch or override the Serializer in this case. def job_start(request, platform_name="other", script_version="1"): # load in data json_data = json.loads(request.body.decode('utf-8')) jenkins_vars = jenkins_lib(json_data) # create dictionary of key/values required to create Product product_dict = {} product_dict['name'] = jenkins_vars.product product_dict['product_age'] = jenkins_vars.age #create object via DRF serializer = ProductSerializer(data.product_dict) if serializer.is_valid(): serializer.save() # create dictionary of … -
My password is stored inside the email field in Django admin
I have this view that stores data for 2 forms. The data for my second form is fine. But for the main User form, I just wanna store the username, password and have a password confirmation. When a user is created, password gets stored inside the email field for some reason.. class UserForm(forms.ModelForm): password = forms.CharField(label='Password', max_length=32, required=True, widget=forms.PasswordInput) confirm_password = forms.CharField(label='Confirm', max_length=32, required=True, widget=forms.PasswordInput, help_text="Passwords must match!") def clean(self): cleaned_data = super(UserForm, self).clean() password = cleaned_data.get("password") confirm_password = cleaned_data.get("confirm_password") if password != confirm_password: raise forms.ValidationError( "password and confirm_password does not match" ) class Meta: model = User fields = ('username', 'password') exclude = ('email',) ef student_register(request, user): data = dict() if request.method == 'POST': form1 = UserForm(request.POST) form2 = StudentForm(request.POST, request.FILES) if form1.is_valid() and form2.is_valid(): cd1 = form1.cleaned_data user.username = cd1["username"] user.password = cd1["password"] user.confirm_password = cd1["confirm_password"] new_user = User.objects.create_user(user.username, password, confirm_password) new_user.save() cd2 = form2.cleaned_data name = cd2['name'] surname = cd2['surname'] email = cd2['email'] phone = cd2['phone'] student_id = cd2['student_ID'] photo = cd2['photo'] Student.objects.create(user=new_user, name=name, surname=surname, email=email, phone=phone, student_ID=student_id, photo=photo) return redirect('index') else: form1 = UserForm() form2 = StudentForm() data['form1'] = form1 data['form2'] = form2 return render(request, "student_signup_form.html", data) -
Django Custom Form Validation not working
I am trying to get some custom form validation working on Django but its not currently working. class PostCodeForm (forms.Form): pcode = forms.CharField() def clean_pcode(self): permitted = {'a','b','c','d'} pcode = self.cleaned_data['pcode'] if not str(permitted) in pcode: raise forms.ValidationError("Apologies, but surrey Spice does not currently deliver to you postcode.") return pcode The end goal is that anything not in that tuple should not be permitted and should return the validation error. Any help is really appreciated. -
Is possible to route with gunicorn to different endpoint to specific CPU?
I have a endpoint that take a long time to answer. Is just one. I wonder if is possible to route something like: Url(/costly) -> Worker 1 Url(/all) -> Worker 2-4 So my main site not get slow when the /costly endpoint is called. P.D: I run it on docker. I could duplicate the web app and redirect with nginx, but think is wastefull. I now I could use a queue but this requiere a rearchitect of the app and need a stopgap by now.. -
Display one to many relation relations in the template django
I have models in my model.py: And I would like to display and edit these two models in a web page. Someone can help me please. parent: fdt_schedulejour fdt_schedulejour class fdt_schedulejour(models.Model): user = models.ForeignKey(User) date = models.DateField(blank=True, null=True) commentaire = models.CharField(max_length=500, blank=True, null=True) class Meta: managed = False db_table = 'fdt_schedulejour' id = models.AutoField(primary_key=True) def __unicode__(self): return '%s' % (self.date) child: fdt_activite. fdt_schedulejour class fdt_activite(models.Model): schedulejour = models.ForeignKey(fdt_schedulejour) debut = models.TimeField(blank=True, null=True) fin = models.TimeField(blank=True, null=True) class Meta: managed = False db_table = 'fdt_activite' id = models.AutoField(primary_key=True) def __unicode__(self): return '%s' % (self.type) Thank you