Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
How to avoid orphan records in Django many-to-many relationships?
How do you ensure that you don't leave any orphan records when deleting records from Django tables that have a many-to-many relationship? I've created three Django models that will allow users to create lists of items that represent activities (e.g. movies, concerts, and sporting events) they want to attend. Since each user can include one or more items (i.e. activities) in a list and multiple users may have the same item (activity) in one of their lists, there's a many-to-many relationship between lists and items: class Type(models.Model): TYPES = ( (1, 'Movie'), (2, 'Concert'), (3, 'Sport'), ) type = models.CharField(_('type'), max_length=16) class Meta: db_table = 'type' class List(models.Model): user = models.ForeignKey(User) type = models.ForeignKey(Type, help_text=_('Type of list')) name = models.CharField(_('list'), max_length=128, help_text=_('Name of list')) class Meta: db_table = 'list' unique_together = (('user', 'type', 'name'), ) # Ensure no duplicate lists class Item(models.Model): """item contains the pk of a movie, concert, or sporting event record""" lists = models.ManyToManyField(List, related_name='items'). # Results in creation of item_lists linking table type = models.ForeignKey(Type, help_text=_('Type of item')) item = models.IntegerField(_('item'), help_text=_('Item in list')) class Meta: db_table = 'item' unique_together = ('item', type',) Whenever I create a new list item, I'll use Django's get_or_create() QuerySet method. … -
Evaluate Django links inside python if statement
in a template {% if case == "Child" %} <a href="{% url 'child:childViewA' childID=childID %}">Child View A</a> <a href="{% url 'child:childViewB' childID=childID %}">Child View B</a> {% else %} <!-- Parent case--> <a class="nav-item nav-link" href="">No Child currently selected</a> {% endif %} I would like to generate URLs based on whether I have enough information. In a child view situation, I can easily look up a parent, but in a parent view situation, I don't know which child to provide a specific URL for that child (or the many that exist because there are too many childs). How do I get Django to evaluate the urls only when it is in the python case specified? -
Getting all registered users from Django's inbuilt user model into a class within admin.py
I am fairly new to Django and can just about articulate what I am trying to do, so I apologise if the title isn't accurate. I am using this survey app - https://github.com/Pierre-Sassoulas/django-survey Within admin.py, I have the following two classes: class SurveyAdmin(admin.ModelAdmin): list_display = ('name', 'is_published', 'need_logged_user', 'template') list_filter = ('is_published', 'need_logged_user') inlines = [CategoryInline, QuestionInline] actions = [make_published] class ResponseAdmin(admin.ModelAdmin): list_display = ('interview_uuid', 'survey', 'created', 'user') list_filter = ('survey', 'created') date_hierarchy = 'created' inlines = [ AnswerTextInline, AnswerRadioInline, AnswerSelectInline, AnswerSelectMultipleInline, AnswerIntegerInline ] # specifies the order as well as which fields to act on readonly_fields = ( 'survey', 'created', 'updated', 'interview_uuid', 'user' ) These create the pages for "Responses" and "Surveys" in the Admin page. Admin area with Response and Survey links / their outputs I can list the usernames of each user that submitted a Response to the Survey (using TabularInLine and model.response), but what I want to do is list all of the users that exist (so that I can add a timestamp of when they submitted their Response to the Survey/Filter by Response date/etc.). What I've tried since is importing User from contrib.auth.models and creating a new UserAdmin class (so that I can at least … -
Django REST how to display extra data from other models in json response
I have a Task_worker model, which is a through table for 2 models - Worker and Task. Currently GET /task-worker returns the following json: { "count": 3, "next": null, "previous": null, "results": [ { "task": 21, "worker": 1, "created": "" }, { "task": 20, "worker": 1, "created": "" }, ... ] } There is no information about the worker and task, and hence I will need to do extra queries to get information I need to display what I need. For example, GET /tasks/21 returns: { "url": "http://127.0.0.1:8000/api/tasks/21/", "workers": [ { "task": 21, "worker": 1, "created": "2018-01-24T16:47:34.657800Z" } ], "user": "username", "created": "2018-01-24T16:31:33.597255Z", "title": "Help me with Django", } So I would like to return the following in my json from GET /task-worker/ { "count": 3, "next": null, "previous": null, "results": [..., { "id":2, "task": {"title": "Help me with Django"}, "worker": { 'Worker Info' }, "created": "" }, ... ] } CODE SETUP models.py class Task_worker(models.Model): worker = models.ForeignKey(Worker) task = models.ForeignKey(Task) created = models.DateTimeField(auto_now_add=True, blank=True) class Meta: unique_together = ('worker', 'task') serializers.py class TaskWorkerSerializer(serializers.ModelSerializer): task = serializers.ReadOnlyField(source='task.id') #TRIED #task = TaskSerializer(source = task_worker_task, read_only=True) worker = serializers.ReadOnlyField(source='worker.id') class Meta: model = Task_worker fields = ('id', 'task', 'worker', 'created', ) … -
Django Rest Framework API Authentication Test
I'm writing tests to check if the Authenticated users have access to the API Endpoints. On my test settings, I have set the defaults for Rest Framework Authentication and Permissions Classes. The default setting is that everyone has to be authenticated to access the API. REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', )} This is the function which is failing (and all others). Here, I create a user object with a custom UserFactory which is setting a default email and password for each user created. Then I use the APIClient with basic authentication to log in. I'm following the official Django Rest Framework Documentation def test_retrieve(self): user = UserFactory.create() client = APIClient() client.login(email=user.email, password=user.password) entity = AttributeChoiceFactory.create() response = self.get(retrieve=entity.pk) self.assertEqual(response.status_code, status.HTTP_200_OK) item = json.loads(response.content) self.assertEqual(type(item), dict) self.assertEqual(item['pk'], entity.pk) self.assertItemsEqual(AttributeChoiceSerializer.Meta.fields, item.keys()) The test fails with Not Authorized Status Code AssertionError: 401 != 200 -
Forms save. Date time discover interval
I need to discover interval for begin_date and end_date fields of my model class Reserved(models.Model): begin_date = models.DateTimeField() end_date = models.DateTimeField() In short when user is saving some data to the database in forms should be validation. Validation should to check is there reservation in interval begin_date and end_date and give error. I tried to to this but it does not work :( def save(self, commit=True): date_validation = Reserved.objects.filter(room=self.room).exists() and \ Reserved.objects.filter( begin_date__gte=datetime.date.today(), end_date__lte=datetime.date.today() ) if date_validation: raise RuntimeError('You can not reserve this room. Interval') super(ReserveRoomForm, self).save(commit) For example the there are reservation in begin date 23-January and end date 29-January but user trying to reserve in 25-January How to realize it? Thanks) -
Easiest strat to add a Subscribe module to a Mezzanine blog
I have a Mezzanine blog and I would like to add a little form to every page so users can type their email addresses and click 'subscribe' so, from that moment, an email will be sent to announce any new post to the blog. I don't see that built in or any existing module for that purpose... Should I program that from scratch? Any ideas? -
check changes before saving into database
I am using Django 1.11 and DRF 3.6.2 and just started developing an API... I am trying to check what are the changes to be performed in the database with the data being sent. class IndividualViewSet(viewsets.ModelViewSet): """Individual ViewSet.""" serializer_class = serializers.IndividualSerializer queryset = models.Individual.objects.all() def update(self, request, equipment_serial, pk=None): queryset = models.Individual.objects.get(pk=pk) serializer = serializers.IndividualSerializer(queryset, data=request.data["entities"][0]) if serializer.is_valid(): serializer.save() return Response(serializer.data, status.HTTP_200_OK) return Response(status.HTTP_400_BAD_REQUEST) def perform_update(self, serializer): old_obj = self.get_object() new_data_dict = serializer.validated_data if old_obj.name != new_data_dict['name']: # logic for different data # ... serializer.save() However, with the code as above, the perform_update function is never being called by serializer.save() on the update function. My questions surrounds on why it is happen and how should I do in order to accomplish the desired behaviour. -
how serve django media file in shared hosting?
im using django 1.11.4 and i want to serve django media file in a shared host my web server is apache i already set MEDIA_ROOT and MEDIA_URL and evreything is fine when Debug = True i alread try HelioHost wiki and Django serving media files (user uploaded files ) in openshift but it dosnt work -
python-django-restframwork deserializer
I have a list like this form. [{'XPos': {'$': 128.604314661}, 'YPos': {'$': 35.8662354972}, 'clCd': {'$': 1}, 'drTotCnt': {'$': 545}, 'estbDd': {'$': 19100907} }, {'XPos': {'$': 128.096026987}, 'YPos': {'$': 35.1753899647}, 'clCd': {'$': 1}, 'drTotCnt': {'$': 326}, }, {'XPos': {'$': 127.050741243}, 'YPos': {'$': 37.5937747637}, 'clCd': {'$': 1}, 'drTotCnt': {'$': 412}, 'estbDd': {'$': 19711005} }, {'XPos': {'$': 128.582521394}, 'YPos': {'$': 35.8701796577}, 'clCd': {'$': 1}, 'drTotCnt': {'$': 427} }, {'XPos': {'$': 126.884639554}, 'YPos': {'$': 37.4911811753}, 'clCd': {'$': 1}, 'drTotCnt': {'$': 498}, 'estbDd': {'$': 19830831} }, {'XPos': {'$': 126.824997324}, 'YPos': {'$': 37.3188581763}, 'clCd': {'$': 1}, 'drTotCnt': {'$': 281}, 'estbDd': {'$': 19860101}, }] and using django-rest-framework deserializer, i want to insert that data into my database. BUT, i have some problems. I just only need 'XPos','YPos', 'estbDd' value. In converting xml to json, more nested structures have been created. (look '$') Some datas do not have 'estbDd' field values. How can i filter that datas and input to my database? http://www.django-rest-framework.org/api-guide/serializers/ i referenced that site. -
Django: customizing the Form does not deliver the instructions, input only numbers etc
I am in the forms.py file, and as you can see I am trying to customize the html that the template engine renders, but it is ignoring whatever I write. If I enter letters, it should show a dialog box on the fly as HTML5 by default does, indicating that only numbers. Also even if I write a number larger than 10, which is the limit, it sends it anyway. In other words, the customization on the forms.py page is not being effective like when you do it directly on the form. but I cannot write in the form because of the **** template that abstracts everything and you dont know what is going on behind doors. I include the form just for curiosity: class ReForm(forms.Form): count = forms.CharField(widget=forms.TextInput( attrs={'input type': 'number', 'pattern':'\d*', 'maxlength':'2', 'min': '1', 'max':'10','title':'Numbers only','placeholder':'Max value 10'})) FORM: <form method="GET" novalidate> {% csrf_token %} {% for hidden_field in form.hidden_fields %} {{ hidden_field }} {% endfor %} {% for field in form.visible_fields %} <div class="form-group"> {{ field.label_tag }} {% render_field field class="form-control" %} {% if field.help_text %} <small class="form-text text-muted">{{ field.help_text }}</small> {% endif %} </div> {% endfor %} <button type="submit" class="btn btn-primary">Submit</button> </form> -
Django DRF read json from POST?
When I try to send data from a jquery POST I can get them from both side, js client and python django-rest-framework sefializer create method from backend console.log says: { "wo_r": [ { "pk": "17635" }, { "pk": "17637" } ] } the form data show dict as: { "wo_r": [ { "pk": "17635" }, { "pk": "17637" } ] }: django shell read: <QueryDict: {'{\n "wo_r": [\n {\n "pk": "17635"\n },\n {\n "pk": "17637"\n }\n ]\n}': ['']}> Why the data sent get this ":" at the end? this is the javascript part: function creaol(indirizzo,val) { $.ajax({ url: indirizzo, type: 'POST', dataType:'json', global: false, data : val, // data : {'wo_r':[ // {"pk": "17629"}, {"pk": "17630"},{"pk": "17631"} // ]}, success: function(result) { // Do something with the result } }); } var dati = JSON.stringify(dict, null, 2); creaol(indirizzo, dati );