Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF: Post request with existing nested objects
I'm new to Django Rest Framework and nested serializers. I have a ModelSerializer named OrderSerialiser which contains two nested ModelSerializers : ProductSerializer and ClientSerializer. I want that new instances of the model client and the model product are created (Only if there is no already existing ones) when a post request is sent to the Order CreateAPI. The solution I have found is to override the create method of the OrderSerializer. It works fine when there is no instances of the client and the product having the same email and sku, but it returns an error saying that there is already existing objects ( client with the same email and a product with the same sku ) in the other case and does not get those existing objects,I noted that the create method in this case is not called , I think that I have to override the serializers.is_valid() method but I didn't figure out what I should do exactly . models.py class Client(models.Model): email = models.EmailField( verbose_name=_('Email address'), max_length=255, unique=True, primary_key=True ) first_name = models.CharField(_('first name'), max_length=30) last_name = models.CharField(_('last name'), max_length=30) class Product(models.Model): sku = models.CharField( verbose_name=_('SKU'), unique=True, max_length=120, primary_key=True ) name = models.CharField( verbose_name=_('Name'), max_length=150 ) url … -
Django auto_now behaviour
I have the following model: class MetaData(models.Model): created_at = models.DateTimeField(auto_now_add=True, auto_now=False) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, related_name='%(app_label)s_%(class)s_created_by') updated_at = models.DateTimeField(auto_now_add=False, auto_now=True) updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, related_name='%(app_label)s_%(class)s_updated_by') The update_at field is also completed with a value at the creation time instead of being null. I expected to have a value, only after the first save/creation. Am I doing something wrong ? -
Is there a way to see context data given to the template?
usually there is a views or a url pattern that sends context to a tamplate. This is all fair and good when the code you are implementing is your own. But right now im finding myself implementing allauth and im not sure about the context "keys" (not sure if thats the right word, but i mean something like "user.is_authenticated") I can use in the template. One way of finding out which context objects are given to the template is to find the get_context_data function in the source code of the code that I am using. But is there a faster way to see the context given to the template? regards -
Two actions on the same page
At the moment, I have two functionalities on two pages: List all orders(/orders) Create a new order(/create) I would like to to be able to create an order on the same page as listing. In my urls.py: url(r'^create/$', views.OrderCreateView.as_view(),name='create'), In my forms.py: class OrderCreateForm(forms.ModelForm): class Meta: model = models.TransDetails fields = ("__all__") In my views.py: class PlaceListView(LoginRequiredMixin,ListView): login_url = '/login/' context_object_name='placeList' model= models.Places template_name = 'transadmin/place_list.html' def get_queryset(self): return models.Places.objects.all().order_by('pname') class PlaceCreateView(LoginRequiredMixin,CreateView): login_url = '/login/' form_class = PlaceCreateForm success_url = reverse_lazy("transadmin:place_list") template_name = 'transadmin/create_place.html' I have tried adding a form on the listing page to add but when submit nothing is happening. How do I go about this? -
Duplicate entry for a ManyToManyField
I have a form to create a new user. Once the user is created, It create a Profil for it. In the model of the Profil, I have a ManyToManyField. Until now, everything works fine. Then I automatically login the user and I insert into the ManyToManyField. And so I have an error : IntegrityError at /start/register/ (1062, "Duplicate entry '50' for key 'user_id'") This my model : class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birthdate = models.DateField(null=True, blank=True) avatar = models.FileField(upload_to=user_directory_path, validators=[validate_file_extension], blank=True, null=True) sex = models.CharField(max_length=12, null=False) favori = models.ManyToManyField(Games, verbose_name="Jeu") And in my view : favoris = favori_form.save(commit=False) favoris.user = request.user favori_form.save() First I tried this : favoris = favori_form.save(commit=False) favori_form.save() But an error message told me that the save method required a user instance. That's why I added : favoris = favori_form.save(commit=False) favoris.user = request.user favori_form.save() More details, this is my forms.py : class GamesChoiceField(ModelMultipleChoiceField): def label_from_instance(self, obj): media = settings.MEDIA logo = '<img src="%s{url}"/>'.format(url=obj.logo) %(media) return mark_safe("{logo} {title}".format(title=obj.title, logo=logo)) class GamesRegisterForm(forms.ModelForm): game = Games.objects.all() favori = GamesChoiceField(widget=forms.CheckboxSelectMultiple, required=True, queryset=game) class Meta: model = Profile fields = ('favori', ) -
"relation does not exist" when creating new status check
I'm using Cabot monitoring application which using django. A class for basic status check inherits from PolymorphicModel I've made a new class "Test" which inherits from basic status check class (Multi-table inheritance), which adds few additional fields. The problem is, when I saving new status check object to DB, I get relation "cabot_check_test_teststatuscheck" does not exist. Could you please give me a clue what am I doing wrong? -
Connect to django server from all devices in local network [duplicate]
This question already has an answer here: About IP 0.0.0.0 in Django 3 answers I run the default-server on my Mac. The computer has Firewall disabled. I can't establish a connection by from phone (Android OS) to http://127.0.0.1:8000/. The phone is on the same Network -
How does Django RESTful Framework get user model from token from HTTP header?
I'm building my Django RESTful Framework to retrieve and post data for Mobile. I'm using djang-rest-auth (which is just all-auth with RESTful functionality; more info : http://django-rest-auth.readthedocs.io/en/latest/). How does Django RESTful Framework (or Django) finds user's model when mobile sends user's token in HTTP header? For instance, HTTP METHOD: POST headers : Authorization eyl3of9iskjfpjowpefjsopeff (This is token and random string) body : { post_title: "This is my first post" post_content: "This is the content" } Thanks! -
How to connect web server using own domain in apache2 for django frame work
I am going to connect my project to server using apache2. This is my code in domainname.conf file: <VirtualHost *:80> LoadModule wsgi_module modules/mod_wsgi.so WSGIScriptAlias / /var/www/<project>/<project>/wsgi.py ServerName <domainname.com> Alias /static /var/www/<project>/static/ <Directory /var/www/<project>/> Order allow,deny Allow from all </"Directory> </VirtualHost> Finally, I run a server but it's not connecting. -
How to define m2m_reverse_name_cache?
I need to have a custom relation table for a OneToOne relation between two version of elements inheriting the same model (no matter what the model is). For this, here is model and the relation model. class Ensemble(models.Model): name = models.CharField("Nom", max_length=50) version = models.CharField("Version", max_length=10, blank=True, default=None, null=True) parent_version = models.OneToOneField("self",verbose_name="Version du parent", default=None, blank=True, null=True, related_name="children_version", unique=False) version_up = models.ManyToManyField('Ensemble', through='Version_up', symmetrical=False, blank=True, related_name='version_up_set') class Version_up(models.Model): child_element = models.ForeignKey(ContentType ,on_delete=models.CASCADE, blank=True, null=True, related_name="child_element") parent_element = models.ForeignKey(ContentType, on_delete=models.CASCADE, blank=True, null=True, related_name="parent_element") description = models.TextField(max_length=1000, verbose_name="Commentaires", default=None, blank=True, null=True) child_id = models.PositiveIntegerField() parent_id = models.PositiveIntegerField() child_content = GenericForeignKey('child_element' ,'child_id') parent_content = GenericForeignKey('parent_element', 'parent_id') However when I try to access the manager of an Ensemble model, I got this error : {AttributeError}'ManyToManyField' object has no attribute '_m2m_reverse_name_cache' I've read AttributeError: 'ManyToManyField' object has no attribute '_m2m_reverse_name_cache' this post but it doesn't apply to my issue, as I need to store extra data concerning the relation. Thanks in advance for any help. -
Django-cms template error in Django 1.4 project
I'm trying to run locally old Django 1.4 project which I have to upgrade and further develop. Everything is working fine on server. On my local I've got virtual environment set up using pip freeze from project on server and pip install. Project is using django-cms 2.3.8. Opening 127.0.0.0:8000 produces error: Template error: In template /home/user/projects/mprj/src/project/templates/menu/main_menu.html, error at line 6 A template tag couldn''t find the page with lookup arguments `{'reverse_id': u'polls', 'site': 1} `. The URL of the request was: http://example.com/ 6 : <a href=" {% page_url "polls" %} " title="{% page_attribute "title" "polls" %}"> {% page_attribute "title" "polls" %} </a> Traceback: ... File "/home/user/.virtualenvs/mprj/local/lib/python2.7/site-packages/cms/templatetags/cms_tags.py" in get_context 115. page = _get_page_by_untyped_arg(page_lookup, request, site_id) File "/home/user/.virtualenvs/mprj/local/lib/python2.7/site-packages/cms/templatetags/cms_tags.py" in _get_page_by_untyped_arg 86. raise Page.DoesNotExist(body) Exception Type: DoesNotExist at / Exception Value: A template tag couldn''t find the page with lookup arguments `{'reverse_id': u'polls', 'site': 1} `. The URL of the request was: http://example.com/ Error occurs on {% page_url "polls" %}. It's not clear for me, where should 'reverse_id' be set. I can't figure it out from django-cms docs. Also it doesn't seem to be issue of http://example.com/ URL. Error still occurs when I add 127.0.0.1:8000 site to database and set corresponding SITE_ID in … -
Remove mistakenly added primary key on OneToOneField Django
class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, primary_key=False) profile_pic = models.FileField() about_user = models.TextField(blank=True) def __str__(self): return self.user.get_short_name() i think there is no use of setting primary key to my userobjects as it is already by default.......please help me' and also tell me django automatically assigns a primary key as 1 by default in id row of table of model .... -
Deploying old Django site to new server
I've been handed a dump of a Django site that I'm trying to help restore on a new server for a friend. I'm not really experienced with Django, which is why I probably need some dumbed-down answers for this. I do have a dump of the database seperately, but for now I'm just trying to restore the app itself. In the main dir of the dump (/home/naturligvis), there is a "public_html" dir, with a "hander.wsgi" file in it, that has the following code: import os import sys for path in ('/home/naturligvis/lib/python/PIL/', '/home/naturligvis/lib/python/', '/home/naturligvis/naturligvis-bzr/modules/',): if path not in sys.path: sys.path.insert(0, path) os.environ['DJANGO_SETTINGS_MODULE'] = 'naturligvis.psisettings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() Now I'm trying to figure out what kind of setup I need to do on a server (Trying with Ubuntu 16.04 on DigitalOcean) in order to make this work...? All the settings.py etc. files are in /home/naturligvis/naturligvis-bzr/modules/naturligvis Hoping that someone can help me or point me in the right direction. -
Running application on the client system, django
I have a laptop (as a server) and a Raspberry pi 3 (as a client). What i want is to exchange and run files between them, that is, run an application on the raspberry pi through a command from the server, and receive the output of that application in txt file back to the laptop (server) . Both are on the same network. Is there any way to do this..? -
'WSGIRequest' object has no attribute 'FILE'
I want to make an app that takes excel file and reads its content, without using form and models. I keep getting the error in the title and I would to know what the error is. This is my HTML: <div style="width: 800px; margin: 0 auto;"> <form enctype="multipart/form-data" action="." method='POST'> {% csrf_token %} <input type="file" name="excelfile"> <input type="submit" value="Submit" /> </form> </div> This is my view: def uploadexcelfile(request): if request.method == "POST": excel = request.FILE['excelfile'].read() print('Opening workbook...') wb = openpyxl.load_workbook(excel) activesheet = wb.active print(activesheet.title) sheet = wb.get_sheet_by_name(activesheet.title) print('Reading rows...') for row in range(1, sheet.max_row + 1): url = sheet['A' + str(row)].value print(url) else: return render(request, 'uploadexcelfile.html') -
How to set cookie in Django with Ajax request?
How can I set a cookie, when I have no response object? This is the Ajax: $("#login-box-login-button").click(function (e) { $.ajax({ url: "/api/check/login", data: { "email": $("#login-box-email").val(), "pass": $("#login-box-password").val(), }, success: function (data) { // ... }, error: function (data, exception) { // ... } }); }) And here is the view which the request above is calling: def check_login(request): """ Will check whether the passed login data is correct. """ email = request.GET["email"] password = request.GET["pass"] customer = # Somehow get him if check_password(password, customer.password): # Create cookie here pass -
Django, where should the code go? views or models
I have a bunch of REST views and a bunch of data transfers posted from templates that needs to be cleaned. I am wondering where to put all the sanitizing code and processing code should go: views.py or models.py ? Am I missing some secret tricks that I don't know about? (like usage of model.manager) ? Currently I kept the models clean with object creation and update. Views is nicely organized with strictly REST views. But as the project grows, more and more code, especially handling of data that has accumulated. (views.py file had grown in size to 150lines) Should I put them in another file. If so, is that ok to pass the whole "request" to that file? (along with having to import models and possibly sessions and messages) -
Send account details to user email from django admin
I am trying to send an email to a user after the user account is created by the admin. accounts/admin.py class ProfileInline(admin.StackedInline): model = Profile can_delete = False verbose_name_plural = 'Profile' fk_name = 'user' class CustomUserAdmin(UserAdmin): inlines = (ProfileInline, ) list_select_related = ( 'profile', ) list_display = ('email', 'username', 'first_name', 'last_name', 'is_staff') fieldsets = ( ('Personal information', {'fields': ('first_name', 'last_name', 'username', 'email', 'password')}), ('Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), ('Important dates', {'fields': ('last_login', 'date_joined')}), ) add_fieldsets = ( ('None', { 'classes': ('wide',), 'fields': ('username', 'email', 'password1', 'password2')} ), ) def get_inline_instances(self, request, obj=None): if not obj: return list() return super(CustomUserAdmin, self).get_inline_instances(request, obj) def get_ordering(self, request): return ['-date_joined'] def save_model(self, request, obj, form, change): super(CustomUserAdmin, self).save_model(request, obj, form, change) obj.user = request.user obj.profile.email_confirmed = True obj.profile.save() print(obj) if not change: current_site = get_current_site(request) subject = 'Your Account Login Details' message = render_to_string('accounts/email/account_detail_email.html', { 'user': obj.user, 'domain': current_site.domain, }) obj.user.email_user(subject, message) Email header MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: 7bit Subject: Your Account Login Details From: ****@gmail.com To: admin@admin.com Date: Wed, 23 Aug 2017 11:21:41 -0000 Message-ID: <20170823112141.16912.15261@DESKTOP-BRG5003> The email should go to user email not to the admin and from email should be the admin email. when I print obj … -
Python (Django): ImportError: No module named ' '
I have different scripts in the following diretory structure (see picture): Directory crawl.py imports script db.py from the same directory. However, I receive an error message: ImportError: No module named 'db'. I tried to rename the script, but the same error still exists. crawl.py import db import sys import requests import json from datetime import datetime def query(resource): r = requests.get('http://10.105.11.20:8080/webapp/api/v1/' + resource, headers={'AuthenticationToken': 'c9e52cb6-95b4-4ae3-b4bb-4cde692f3a4e'} ) return r def crawlmain(formdata): costumer_id = 1 production_number = formdata d = query('productionOrder/?productionOrderNumber-eq={}'.format(production_number)).json() session = db.Session() costumer = session.query(db.Costumer).get(costumer_id) if 'result' in d and len(d['result']) > 0: r = d['result'][0] order = db.Order() try: order.article_id = r['articleId'] order.amount = r['targetQuantity'] order.create_date = datetime.fromtimestamp(r['createdDate'] / 1000) order.start_date = datetime.fromtimestamp(r['targetStartDate'] / 1000) order.end_date = datetime.fromtimestamp(r['targetEndDate'] / 1000) except NameError as e: sys.exit('Error {}'.format(e.what())) article_number = r['articleNumber'] d = query('article/?articleNumber-eq={}'.format(article_number)).json() if 'result' in d and len(d['result']) > 0: r = d['result'][0] article_image_id = r['articleImages'][0]['id'] order.price_offer = r['articlePrices'][0]['price'] r = query('article/id/{}/downloadArticleImage?articleImageId={}'.format(order.article_id, article_image_id)) order.article_image = r.content else: print('No result for article with number', article_number) costumer.orders.append(order) session.add(costumer) session.commit() else: print('No result for production order with article number', article_number) It might be important to say, that the script runs without problems if carried out as a standalone script (though still stating … -
Django Error Messages
I am new in Django and i have one problem. Using django forms and can not get error message in cycle. They just does not appear. I don't know why this happens but i have changed generating of form. In short look to code <span id="username" class="input input--madoka">{{ form.username }} {{ form.username.label_tag }}</span> <span id="first_name" class="input input--madoka">{{ form.first_name }} {{ form.first_name.label_tag }}</span> <span id="last_name" class="input input--madoka">{{ form.last_name }} {{ form.last_name.label_tag }}</span> <span id="email" class="input input--madoka">{{ form.email }} {{ form.email.label_tag }}</span> <span id="password" class="input input--madoka">{{ form.password1 }} {{ form.password1.label_tag }}</span> <span id="password2" class="input input--madoka">{{ form.password2 }} {{ form.password2.label_tag }}</span> {% for error in form.errors %} <h2 style="color: red; font-size: 50px">{{ error }}</h2> {% endfor %} Just error messages does not appear. Thanks in advance. (Sorry if i gave question wrong.) Beginner :( -
Is Django multiple unique_together wrongly mapped in PostgreSQL?
When I add multiple unique_together tuples in my django model, the PostgreSQL DB mapping appears wrong (also according to a previous SO answer on the subject). An example follows. This is my migration: migrations.CreateModel( name='FinancialConcept', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('taxonomy', models.CharField(max_length=128)), ('name', models.CharField(max_length=256)), ('xbrl_element', models.CharField(max_length=256)), ('parent', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='analysis.FinancialConcept')), ], ), migrations.AlterUniqueTogether( name='financialconcept', unique_together=set([('taxonomy', 'name'), ('taxonomy', 'xbrl_element'), ('parent', 'xbrl_element')]), ), .... which I expected would create three UNIQUE indexes, one for each pair. But instead, what the DB mapping ends up being is this: Column | Type | Modifiers --------------+------------------------+------------------------------ ------------------------------------------ id | integer | not null default nextval('analysis_financialconcept_id_seq'::regclass) taxonomy | character varying(128) | not null name | character varying(256) | not null xbrl_element | character varying(256) | not null parent_id | integer | Indexes: "analysis_financialconcept_pkey" PRIMARY KEY, btree (id) "analysis_financialconcept_taxonomy_xbrl_element_d8b45254_uniq" UNIQUE CONSTRAINT, btree (taxonomy, xbrl_element) "analysis_financialconcept_parent_id_51fc8021" btree (parent_id) I.e, one of the UNIQUE indexes is right, but the other two are missing. Any idea what is causing this? -
Django open an application external html file on the same server
In my django project i have a routine that, through an external library generate a log.html file. I would open this file using a button in my django app template but if i pass the path es: 127.0.0.1:8000/core/out/11098276/log.html django give me an error that in urls.py the out/ path is not defined. I try to define an url like this: in urls.py url(r'^out/', render_lib), and in views.py @login_required def render_lib(request, **kwargs): return render_to_response(request) but i receive the error: [Errno 22] Invalid argument: u"C:\Code\lyraProject\lyra\core \templates\WSGIRequest: GET '\out\105828816\log.html'>" How can i open an external html file on my server from django?? Thanks in advance -
Can I save my Django signals in an empty app
I want to implement signals for a number of my apps and for django-contrib-comments. Can't I just create an app, load it at the top of settings.INSTALLED_APPS (After the django apps) and then place all my signals inside the views.py file? # > ./manage.py startapp signals # > vim myapp/settings.py ... INSTALLED_APPS = { ... 'signals', ... } ... # > vim signals/view.py ... from django.db.models.signals import post_save from django.dispatch import receiver from myapp.mymodels import MyModel @receiver(post_save, sender=MyModel) def MyModelSaveSignal(sender, **kwargs): ... ... -
How to create radio buttons in django which fields use in form and model
I am new to Django,python.I want to add radio button in my form but it doesn't works . forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.forms.widgets import RadioSelect from choicebtn.models import myChoice class myChoiceForm(UserCreationForm): name=forms.CharField(max_length=55) TYPE_SELECT = (('0', 'Female'),('1', 'male'),) gender=forms.ChoiceField(widgets.RadioSelect(choices=TYPE_SELECT)) class Meta: model = myChoice fields = ['name','gender'] and my model.py from django.db import models from django.forms.widgets import RadioSelect from django.urls import reverse class myChoice(models.Model): name=models.CharField(max_length=55) TYPE_SELECT = (('0', 'Female'),('1', 'male'),) gender=models.CharField(max_length=11,choices=TYPE_SELECT) This only shows dropdownlist and textbox doesn't show radio button. Please help me. -
Django 1.11 giving Server 500 error when debug is false in development
Please I need help on this. I am trying to deploy my application on heroku, but if i set the debug to 'False', I get a 500 error. So I tried it on development and gave me thesame error. I have set the ALLOW_HOSTS variable in the settings and everything seem to just work fine if debug is True.