Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix "Page not found (404)" error ("Django tried these URL patterns... The empty path didn't match any of these.")
As a newbie to Django, I encountered the same problem as many before me. I would appreciate if you didn't mark my question as a double immediately because I checked the fixes those old posts suggested but to no avail. I was following this tutorial and have finished with all up to the heading "Projects App: Templates". Now when I start the server, at http://localhost:8000/ I get: Page not found (404) Request Method: GET Request URL: http://localhost:8000/ Using the URLconf defined in personal_portfolio.urls, Django tried these URL patterns, in this order: admin/ projects/ The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. This is console output when I run server: System check identified no issues (0 silenced). April 05, 2019 - 15:31:54 Django version 2.2, using settings 'personal_portfolio.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Not Found: / [05/Apr/2019 15:32:01] "GET / HTTP/1.1" 404 2042 Not Found: /favicon.ico [05/Apr/2019 15:32:01] "GET /favicon.ico HTTP/1.1" 404 2093 What I tried, but didn't help: restarting the server, checking my code inside the files against … -
Cleaned data displays only the last formset data
I have a django project where I am creating a dashboard using django admin and making requests to an API using requests library. I am also using formsets to create multiple forms dynamically. When I make a post request and observe the data using ipdb, I find that the data from the first n-1 formsets isn't there in the cleaned data. Only the data from the last form is being added to the json. How do i make data from all the forms appear in the json. Here's my code, #forms.py class CampaignForm(forms.Form): consumer = forms.CharField(label="Consumer", max_length=200) startDate = forms.DateTimeField(label="Start Date", input_formats=['%d/%m/%Y %H:%M']) endDate = forms.DateTimeField(label="End Date", input_formats=['%d/%m/%Y %H:%M']) referreeCredits = forms.IntegerField(label="Referree Credits") referrerCredits = forms.IntegerField(label="Referrer Credits") maxReferreeCredits = forms.IntegerField(label="Max Referree Credits") maxReferrerCredits = forms.IntegerField(label="Max Referrer Credits") message = forms.CharField(label="Message", max_length=200) kramerTemplateId = forms.CharField(label="Kramer Template ID", max_length=200) paymentMode = forms.ChoiceField(label="Payment Mode", choices=[("PAYTM","PAYTM")]) class RuleForm(forms.Form): eventName = forms.CharField(label="Event Name", max_length=200) operator = forms.ChoiceField(label="Operator", choices=[("EQUAL","EQUAL"), ("EVERY","EVERY")]) value = forms.IntegerField(label="Value") class MilestoneRulesForm(forms.Form): moperator = forms.ChoiceField(label="Operator", choices=[("EQUAL","EQUAL"), ("EVERY","EVERY")]) mvalue = forms.IntegerField(label="Value") mreferrerCredits = forms.IntegerField(label="Referrer Credits") Html Template: #html {% block content %} <div class="form_div" style="width:60%;"> <h2>Campaign Form</h2> <form method="POST"> {% csrf_token %} {% for field in form.visible_fields %} <div class="form-group"> {{ field.label_tag }} {% … -
Can't find '__main__' module when running celery with Django / virtualenv
Debian 9.8 virtualenv 16.4.3 Python 3.5.3 Django 2.1.7 celery 4.3.0 django-celery-beat 1.4.0 When I run celery commands from my app directory with my venv active like celery worker -A personnel or celery beat -l info --scheduler django_celery_beat.schedulers:DatabaseScheduler, it works as expected. My app's name is 'personnel'. There are several related issues but nothing exactly like mine. Here is what happens when I try various commands. celery worker from the project directory with venv active starts the worker and looks as the documentation shows it should (redis is working, beat works as well) /home/www/personnel/venv/bin/python from outside of the proj dir with venv not active drops me into a shell where I can import Celery without errors /home/www/personnel/venv/bin/celery from outside the proj shows me the celery help (usage: celery [options]...) /home/www/personnel/venv/bin/python /home/www/personnel celery worker, which from my research is what should be working, returns: /home/www/personnel/venv/bin/python: can't find '__main__' module in '/home/www/personnel' The above error is returned even with the -A flag. /home/www/personnel/venv/bin/python /home/www/personnel/manage.py celery worker returns: Unknown command: 'celery' Type 'manage.py help' for usage. The stdout log shows the same errors. I am guessing the command should work before supervisor comes into play. I have started from scratch and recreated the venv … -
Design REST API
I'm designing API for my web application with django-REST, and frontend with Vue.js. There are several "catalog" models. Each catalog item has id field and can have link field to other catalog item. Here is example Device item { "id": 1, "serial_num": "xxx", "comment": "", "nomenclature": 2, "device_type": 3 } Nomenclature item { "id": 2, "label": "HP probook 450", } Device_type item { "id": 3, "label": "Laptop", } Full label for Device item must be "device_type + nomenclature" = "Laptop HP probook 450". So, when I need full label for Device item in frontend I must resolve fields "nomenclature" and "device_type", and then I get label. But for each type of object I should make special function to resolve its label. And hierarchy of objects can be much deeper. Maybe I should just add label field in Device object, which will assemble in backend. What is the best practice? -
I cannot update a nested detail model of the current logged user
The problem that I am facing is that the logged user cannot update its nested model fields such as the "AddressModel". I have tried many ways but always shows errors such as "'NoneType' object has no attribute 'address_1' ", " "Profile.address" must be a "AddressModel" instance." or "could not convert string to float: ". class UserProfileSerializer(serializers.ModelSerializer): """ User Profile model w/o password """ avatar = serializers.ImageField(required=False) address = AddressSerializer(allow_null=False, default='') class Meta: model = Profile fields = ( 'id', 'avatar', 'username', 'email', 'first_name', 'last_name', 'gender', 'age', 'phone', 'address' ) read_only_fields = ('email', ) def update(self, instance, validated_data): address_data = validated_data.pop('address') # this line shows this error 'NoneType' object has no attribute 'address_1' ",. instance.address.address_1 = address_data.get('address_1', instance.address.address_1) instance.address.save() # this part will show this error "could not convert string to float: ". address_1 = address_data.get('address_1', None) instance.address = AddressModel(address_1=address_1) instance.address.save() instance.avatar = validated_data.get('avatar', instance.avatar) instance.username = validated_data.get('username', instance.username) instance.email = validated_data.get('email', instance.email) instance.first_name = validated_data.get('first_name', instance.first_name) instance.last_name = validated_data.get('last_name', instance.last_name) instance.gender = validated_data.get('gender', instance.gender) instance.age = validated_data.get('age', instance.age) instance.phone = validated_data.get('phone', instance.phone) instance.save() return instance This is my view. class UserProfileViews(generics.RetrieveUpdateAPIView): """ Reads and updates Profile fields Accepts GET, PUT, PATCH methods. Default accepted fields: avatar, username, first_name, last_name, gender, … -
How can i make jsp or txt file in django form?
I would like to save the data sent from the form as a txt file to the server. It's not working save /admin too how can i solve this problem? django 2.1, python 3.7 i've tried save DB, but it cant save view.py class task_generation_view(FormView): form_class = TaskGenerationForm model = TaskGeneration fields = '__all__' template_name = "task_generation.html" success_url = reverse_lazy('data_upload') models.py class TaskGeneration(models.Model): classification = '분류 알고리즘' regression = '회귀 알고리즘' clustering ='군집화 알고리즘' detection = '이상치 탐지 알고리즘' reinforce ='강화학습 알고리즘' SELECT_ALGORITHM_CHOICES = ( (classification, '분류 알고리즘'), (regression,'회귀 알고리즘'), (clustering, '군집화 알고리즘'), (detection, ' 이상치 탐지 알고리즘'), (clustering,' 강화학습 알고리즘'), ) algorithm = models.CharField(max_length=30, choices = SELECT_ALGORITHM_CHOICES, default = classification) readyData = models.BooleanField() urls.py urlpatterns = [ #url('$', ModelingView_model.as_view()), url('task_generation', task_generation_view.as_view()), url('data_upload', data_upload_view.as_view(), name='data_upload'), url('data_load', data_load_view.as_view()), url('data_exploration', data_exploration_view.as_view(), name='data_exploration'), url('data_variable_Identification', data_variable_identification_view.as_view()), # url('', FileUploadView.as_view(), name='upload'), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) forms.py class TaskGenerationForm(forms.ModelForm): class Meta: model = TaskGeneration fields = ('algorithm', 'readyData') widgets ={ 'algorithm' : forms.Select(attrs = {'class' : 'btn btn-info btn-select btn-select-light'}), } task_generation.html <form method = "post" enctype="multipart/form-data"> ... {% csrf_token %} {{ form.algorithm }} ... {% csrf_token %} {{ form.readyData }} <button type="submt">submit</button> </form> i want save data in db or server txt file -
django query with distinct ForeignKey
I have two models: class Gallery(models.Model): site = models.ForeignKey(Site, related_name='galleries', on_delete=models.CASCADE) created = models.DateTimeField(_('created'), auto_now_add=True) class Photo(models.Model): image = ImageField(verbose_name=_('image'), upload_to=upload_path) gallery = models.ForeignKey(Gallery, related_name='photos', on_delete=models.CASCADE) created = models.DateTimeField(_('created'), auto_now_add=True,) I want to get three last added photos. Every photo should be assigned to the different gallery. This solution works but it is also very slow. Can I make it work faster? limit = 3 photos = Photo.objects.annotate( max_gallery_created=Max('gallery__photos__created'), ).filter( gallery__site=site, created=F('max_gallery_created'), ).order_by( '-max_gallery_created', )[:limit] I will also be satisfied if I get one last added photo from each of the three last created galleries. I tried to do this that way: galleries = Gallery.objects.filter(site=site).order_by('-created').values_list('id')[:limit] photos = Photo.objects.filter(id__in=galleries) But it doesn't prevent galleries re-occurrance. I thought about using distinct() some way but I don't know how ecaxtly. Django 1.11. -
Django Admin Model on add fails to render related change link
Given following admin settings: class BrokerLocationSetForm(forms.ModelForm): class Meta: model = BrokerLocationSet fields = ('broker', 'program', 'label', 'locations') widgets = { 'locations': autocomplete.ModelSelect2Multiple(url='admin-autocomplete-location', forward=('broker','program')), } class BrokerLocationSetAdmin(admin.ModelAdmin): model = BrokerLocationSet form = BrokerLocationSetForm list_display=['broker', 'program', 'label'] admin.site.register(BrokerLocationSet, BrokerLocationSetAdmin) When I try navigate to add view in admin for BrokerLocationSetForm it raises following error: raise NoReverseMatch(msg) NoReverseMatch: Reverse for 'program_program_change' with arguments '(u'__fk__',)' not found. 1 pattern(s) tried: [u'admin/program/program/(?P<program_pk>\\d+)/change/$'] When I debug in shell: reverse('admin:broker_broker_change', 'myapp.urls', args=(u'__fk__',)) it outputs: u'/admin/broker/broker/fk/change/' but for: reverse('admin:program_program_change', 'myapp.urls', args=(u'__fk__',)) I get same error as above. After some debugging I sensed that somehow admin was passing a string instead of an int into reverse function while it expected an integer as below : reverse('admin:program_program_change', 'myapp.urls', args=(u'1',)) u'/admin/program/program/1/change/' Since django admin does this url reversing magic I am not sure where I should customize this to fix the bug. I have got this code base fairly new and to get sense completely. How I can fix above bug by customizing admin model or form. I dont want to update 'admin:program_program_change' but probably provide an alternate route to same view! . Is it possible ? please advise ! -
Injecting dependencies into INSTALLED_APPs from reusable app
I've recently been spinning a collection of Django apps into a namespace so that we can reuse them for multiple deployments, with different settings, media files, etc. The core of this has worked well. We can make a new Django project, and include all the apps (from our namespace) that we want in settings.INSTALLED_APPS. The problem I'm trying to fix is that we also have to explicitly include the Django apps that our namespaced apps depend on. Eg, where we currently need: INSTALLED_APPS = [ 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.messages', 'import_export', 'rest_framework', 'reversion', 'crispy_forms', 'our_namespace.our_app', ] I would like to be able to reduce this to: INSTALLED_APPS = [ 'our_namespace.our_app', # brings all its dependencies with it ] Other settings are easier to handle, but injecting into INSTALLED_APPS seems hard. Doing it from AppConfig.ready() doesn't seem to work because —if for no other reason— that only runs after models have imported (which is commonly too late). What are my options here? Am I just being too lazy this time? -
CORS issue in Angular2 when joining the Django and Angular
I create one department table using Django and I learn Angular2 . I want to join the Django localhost:8000 to Angular2 localhost:4200 at that time I want to display department table records in Angular localhost:4200. but I got CORS issue warning so please somebody help me. -
How to keep navbar, content and footer as 3 part in the main page with their own height?
I am confused with the way of implementing different html files and css file in structure of project. The problem is that I am not sure if it is a good idea to put all the html files as a different files in Django structure and extend them into one main body ? I already create 3 different files, one incluing html code for navbar, one html file contain content inside main container, and last main file for whole base view. Is it a good way to creating that file structures, which all single files contatining html for each part of page, and each css file to style it ? Or should I include one file for all the html content, and one css file to style it ? Here is a solution I already have: 1.PART OF CONTENT {% extends "base.html" %} {% block content %} <div class="container"> <div class="row"> {% for title in titles %} <div class="col col-sm-3">{{ title.title }}</div> {% endfor %} </div> <div class="row"> <div class="col col-sm-3">col 2</div> <div class="col col-sm-3">col 2</div> <div class="col col-sm-3">col 2</div> <div class="col col-sm-3">col 2</div> </div> <div class="row"> <div class="col col-sm-3">col 3</div> <div class="col col-sm-3">col 3</div> <div class="col col-sm-3">col 3</div> <div … -
Converting datetime to date within html template
I have a datetime field in my models/db in the form strftime('%Y-%m-%d %H:%M:%S'). On my HTML template, i want it to be just the date in the form '25 Dec 2000'. However, if i change from {{ model.datetime }} to {{ model.datetime|date:'d F Y' }}, the field on the html template then goes blank. How do i resolve this? -
Allow hypens in Django Rest Framework serializer field names
Given an OpenAPI specification that I'm writing code against that requires hyphen-case (aka kebab-case) variable names in request bodies, how should this be handled when using Django Rest Framework? For example, a request POST /thing to create a Thing has this body: { "owner-type": "platform" } But in Python, owner-type is not a valid variable name ("SyntaxError: can't assign to operator"), so instead Thing has owner_type in the model definition: class Thing(models.Model): owner_type = models.CharField(max_length=8) But now the ThingSerializer is problematic because, again, owner-type is an illegal name. This is not allowed: owner-type = serializers.CharField(...) I've tried to override how the names are generated in the ModelSerializer by trying to adjust the field names generated by get_fields(), but it failed. Here's my serializer: class ThingSerializer(serializers.ModelSerializer): class Meta: model = Thing fields = [ 'owner_type', ] def get_fields(self): fields = super().get_fields() out_fields = OrderedDict() for field_name, field in fields.items(): out_fields[field_name.replace('_', '-')] = field return out_fields And the error: ../venv/lib/python3.6/site-packages/rest_framework/fields.py:453: in get_attribute return get_attribute(instance, self.source_attrs) ../venv/lib/python3.6/site-packages/rest_framework/fields.py:101: in get_attribute instance = getattr(instance, attr) E AttributeError: 'Thing' object has no attribute 'owner-type' So my question - how can I configure a DRF model serializer to allow Thing.owner_type to be read / writeable by passing … -
New chat message notification Django Channels
I've got Django Channels 2.1.2 set up in my Django app by following a tutorial and now need to set up a notification system for new messages. I want to do this in the simplest way possible (ideally using native Django features if possible...etc Django templating). I've looked around the internet but there isn't a clear tutorial/explanation anywhere for doing this with Django Channels. One answer on here said For notifications you only need two models: User and Notification. On connect set the scope to the currently authenticated user. Set up a post_save signal on your Notification model to trigger a consumer method to message the notification object's user. – I am struggling to wrap my head around what this would look like, I already have a User model but no Notification one. Would I have a signals.py in my chat app which looked something like @receiver(post_save, sender=User) def create_notification(sender, instance, created, **kwargs): if created: Notification.objects.create(user=instance) What would the front end look like? This is obviously all in-app and not via emails. Would I save any instances of the Notification model (generated by post_save signals.py) to my database and then render out that figure using Django templating in the top … -
How to show value of django field conditionaly from child or parent model
I have the following parent model class Parent(Model): value1 = models.CharField(max_length=50) value2 = models.CharField(max_length=50) ....... and the child model class Child(Model) value1 = models.CharField(max_length=10, blank=True, null=True) value2 = models.CharField(max_length=10, blank=True, null=True) ........... how can I return the value of field conditionally? how can I show in templates (tables/lists or details) from parent field if the field with the same name from the child has the value None. And if value of field in child is not None show the value from child. Can I filter data (Childrens) in the same way? Should I use some abstract or proxy models? How? -
Send response to callback url in spyne xml
Is there any example of callback ? like i am receiving request from http://example1.com and i have to give response in this callback url http://example.com , how to use callback in this case ? if anyone have any example of that , please share with me. Thanks -
How to query a row based on a variable that is within the range of 2 fields in my model
I want query a row where my variable is within the range of 2 fields in my model. Supposed I have x = 100 Model = Product with 3 fields price_start, price_end, category. I want to know which category is my 'x' variable. How can i query this in django? p.s. this is just a simplified example of my problem. Supposing price_start and price_end does not overlap, how to know the category. -
How to update the auth email address of the user
I am trying to reset the username of a user registered in my site. The IDE I'm using is Pycharm. With the given code 'email' is the previous email address 'email2' is the new email address. Can someone tell me how to upate the email address . email = request.POST.get('email') email2 = request.POST.get('email2') usernames = database.child("users").get() for user in usernames.each(): userid = user.key() dtls = database.child("users").child(userid).child("details").child('name').get().val() if dtls == email: # user=auth.update -
How does django-admin makemessages parse files?
I am in the process of translating a Django app and I have strings that have to be translated in files of a specific extensions (.vue files, but that's not very important for now). I have to run the makemessages command to parse those strings and generate .po files. The documentation says: makemessages: Runs over the entire source tree of the current directory and pulls out all strings marked for translation. The default file extensions that are included are: html, txt, py. From what I know so far, this is how strings are "marked for translation": .html {% trans "Text to be translated" %} .py gettext("Text to be translated") # or _("Text to be translated") But what about other extensions? .txt, .xml? ... and eventually .vue? -
Django-Anymail not working in docker on Digital Ocean
I am running a django application running on docker and I am using django-anymail to send emails via mailgun. When I go through for example a forgot my password process I am getting an error in django-anymail: AnymailRequestsAPIError: Invalid JSON in Mailgun API response Sending a message to testemail@test.com from info@application.co.uk Mailgun API response 200 (OK): 'Mailgun Magnificent API' @ anymail/backends/base_requests.py in deserialize_json_response at line 106 I am able to re-create this error if I docker exec -it onto the django container and run the following in a: $ python manage.py shell from django.core.mail import send_mail customer_email = send_mail('Test','Test','info@*application*.co.uk',["*test@test.com*"],fail_silently=False) If I run this after building and running my production.yml docker locally it works and I get an email but If I run this on the container on my digital ocean droplet I receive an error. Is there a configuration I am missing in order to get this working? I have another django application just running on a droplet(no docker) and it works fine with mailgun using the same setup. thanks Chris -
How to manage User-Profile creation
I want to create an extended User model. I've created a profile model with a one-to-one relationship with the default django User model. The problem is that when I create a Profile instance and I include the User field it raises me the (NOT NULL constraint failed: portal_profile.user_id) excetion. Why? view.py def register(request): if request.method == 'POST': user_form= UserCreationForm(request.POST) profile_form = ProfileForm(request.POST, request.FILES) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save(commit=False) profile_form.user=user_form profile_form.save() model.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True) img = models.ImageField(null=True, upload_to='userImg') country = models.CharField(null=True, max_length=50) city = models.CharField(null=True, max_length=50) email=models.EmailField(unique=True) forms.py class ProfileForm(ModelForm): img=forms.ImageField(required=False) class Meta: model = Profile fields=['img', 'country', 'city', 'email'] register.html {% if UserForm.errors or ProfileFrom.errros %} <p> Error </p> {% endif %} {{ UserForm }} {{ ProfileForm }} -
Convert s3 video files quality and store it back to s3
I want to convert s3 video file resolutions to other qualities and store it back to s3. I know we can use ffmpeg locally to change the resolution. Can we use ffmpeg to convert s3 files and store it back using Django? I am puzzled as from where to start and what should be the process. Whether I should have the video file from s3 bucket in buffer and then convert it using ffmpeg and then upload it back to s3. Or is there anyway to do it directly without having to keep it in buffer. -
Django timezone not working with postgresql
I want to show user timezone on my django application. The database is on postgresql server. With the configuration below can not reach my goal. Django side: TIME_ZONE = 'UTC' USE_L10N = True USE_TZ = True This is my date field: created = models.DateTimeField(auto_now =True) Postgres side: In my database, the field "created" seems to be aware of timezone: \d my_table; Column | Type created | timestamp with time zone Here is a sample of data stored in this field. it stores the user's timezone and not the UTC: select created from my_table; created ------------------------------- 2019-02-03 10:05:40.462164+02 Additionnel info: - pytz is installed. - my django app shows the UTC time. My question: How can I show the timezone to the user? Do you see that there is something wrong with my configuration? Thanks a lot in advance. -
Remove whitespace and quote marks around option
I'm manually rendering a choice field. <select name="basisofpricing" id="id_basisofpricing"> {% for value, object in form3.basisofpricing.field.choices %} <option value="{{value}}" {% if form3.basisofpricing.initial.id == value %} selected {% endif %} > {{object.basisofrate}} </option> {% endfor %} </select> When I do this, within the browser, the option, when inspected, has quotes and space around it. For example, if Red was one of the options, it would appear like this when being inspected within the browser: <option value="2"> " Red " </option> This spacing and these quotes do not appear on the options' text when I just render the choice field with {{form3.basisofpricing}}. Any thoughts on how I can remove the white spacing and quotes around the option text? Thanks! -
Accessing model through other model via django queryset
I need to access columns in particular table through foreign keys in another table. I wrote it in SQL, but how it will be in queryset language? This is models.py class carModel(models.Model): id_car_model = models.IntegerField(primary_key=True) id_car_mark = models.ForeignKey(carMark,on_delete=models.CASCADE) name = models.CharField(max_length=255) date_create = models.IntegerField(max_length=10,null=True) date_update = models.IntegerField(max_length=10,null=True) id_car_type = models.ForeignKey(carType,on_delete=models.CASCADE) name_rus = models.CharField(max_length=255,null=True) class CarParts(models.Model): id_catalog = models.IntegerField(primary_key=True) manufacturer = models.CharField(max_length=200,blank=True, null=True) vendor_code = models.IntegerField(blank=True, null=True) subgroup = models.CharField(max_length=200,blank=True, null=True) title = models.CharField(max_length=200,blank=True, null=True) side = models.CharField(max_length=200,blank=True, null=True) description = models.CharField(max_length=200,blank=True, null=True) model = models.CharField(max_length=200,blank=True, null=True) trade_mark = models.CharField(max_length=200,blank=True, null=True) original_number = models.CharField(max_length=200,blank=True, null=True) request = models.CharField(max_length=200,blank=True, null=True) price = models.IntegerField(blank=True, null=True) sum = models.IntegerField(blank=True, null=True) availability = models.CharField(max_length=200,blank=True, null=True) class interimTable(models.Model): id_interim = models.IntegerField(primary_key=True) description = models.CharField(max_length=100,null=True) id_catalog=models.ForeignKey(CarParts, on_delete=models.CASCADE) id_car_model = models.ForeignKey(carModel,on_delete=models.CASCADE) This is SQL request, that is successful. I need same thing, but like querySet, to use it in further code. Select title,side,price from carinfo_carparts,carinfo_interimtable,carinfo_carmodel where id_catalog = carinfo_interimtable.id_catalog_id and carinfo_carmodel.id_car_model = carinfo_interimtable.id_car_model_id and carinfo_carmodel.name='Civic'; this is the result