Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django lookup function bug to extract year and week from date
I have defined two django lookup functions @models.DateTimeField.register_lookup class ExtractYear(Extract): lookup_name = 'year' @models.DateTimeField.register_lookup class ExtractWeek(Extract): lookup_name = 'week' I have call it like so : propositions = propositions.annotate(week=ExtractWeek('posting_date'), year=ExtractYear('posting_date')) It gives : Year 2017 , Week : 52 for the date 01/01/2017 I have +5 hours trying to figure out the problem source, who can investigate this ? -
How to include Docker-Sandbox in Django Project?
I am completely new at Django and I am currently working on a Django project. One of my apps need to run untrusted code from users so I decided to use Docker-sandbox which is written in Node js. How do I include this API to my Django Project? -
Django queryset how to exclude products with no group or tags?
Starting from Group, I want to return a queryset of all Groups but only the ones that have products. Models class Group(models.Model): name = models.CharField(max_length=50) class Tag(models.Model): name = models.CharField(max_length=50) group = models.ForeignKey('Group', related_name='tags') class Product(models.Model): name = models.CharField(max_length=50) tags = models.ManyToManyField('Tag', related_name='products') This is what I have tried: Group.objects.all().exclude(tags__products__isnull=True) Above does not appear to return the correct results. I have 2 products with the tags Red and 200cm in Groups color and width but the queryset is 0, why? -
Django UTC Time Not Converting
Im unable to get the UTC time to convert to EST time. I have successfully completed it in my servers shell, but when I do the exact same thing in my view it continues to print out the UTC time, not sure what Im missing. views.py from django.utils import timezone import pytz def today(): today_utc = timezone.now() est = pytz.timezone('US/Eastern') return today_utc.astimezone(est) def projections(request): todays_date = today() context = {'todays_date':todays_date} return render(request, 'index.html', context) and in my template i just do a simple {{todays_date}}, but it continues to print out UTC time. -
Django giving Cannot force an update in save() with no primary key
I'm getting ValueError: Cannot force an update in save() with no primary key. while code hitting to exception and run get_or_create code. Model has it's table in database with auto incremental id field. And also this is not an update process. I can't get why Django behaving like this. ERROR: Traceback (most recent call last): File "x.py", line 1980, in <module> getattr(a, islem)() File "x.py", line 718, in method Slug='undefined', Status=False) File "~/env/local/lib/python2.7/site-packages/django/db/models/manager.py", line 135, in get_or_create return self.get_query_set().get_or_create(**kwargs) File "~/env/local/lib/python2.7/site-packages/django/db/models/query.py", line 385, in get_or_create obj.save(force_insert=True, using=self.db) File ~/core/modules/xx/models.py", line 78, in save super(Categories, self).save(args, kwargs) File "~/env/local/lib/python2.7/site-packages/django/db/models/base.py", line 460, in save self.save_base(using=using, force_insert=force_insert, force_update=force_update) File "x/env/local/lib/python2.7/site-packages/django/db/models/base.py", line 541, in save_base raise ValueError("Cannot force an update in save() with no primary key.") ValueError: Cannot force an update in save() with no primary key. CODE: try: category = Categories.objects.get(Code=category_code) except ObjectDoesNotExist: category, created = Categories.objects.get_or_create( Name='Undefined', Code='undefined',ParentCategoryID=None, OrderID=0, Slug='undefined', Status=False) MODEL: class Categories(models.Model): Name = models.CharField(max_length=155) Code = models.CharField(max_length=255) ParentCategoryID = models.ForeignKey('self', related_name='SubCategory', null=True, blank=True) Level = models.IntegerField(default=0, max_length=10, editable=False) OrderID = models.IntegerField(blank=True, max_length=10) Slug = models.SlugField(max_length=250) CreateDate = models.DateTimeField(auto_now_add=True) LastUpdateDate = models.DateTimeField(auto_now=True) Status = models.BooleanField(default=True) def save(self, *args, **kwargs): if self.ParentCategoryID is not None: parent = Categories.objects.get(id=self.ParentCategoryID.id) self.Level = parent.Level … -
Stop form validation in a formset based on a form checkbox
I have a peculiar issue with designing a view with a formset. Here's the thing: There is a model A: class Model_A(models.Model): field1 = models.ForeignKey(model1) stample = models.DateTimeField(auto_now_add=True) comment = models.TextField(blank=True, default='') # other fields And the Model_B (with Model_A as ForeignKey) class Model_B(models.Model): _modes = (("Mode 1", "Mode 1"), ("Mode 2", "Mode 2"), ("Mode 3", "Mode 3"), ("Mode 4", "Mode 4")) parent_mdl = models.ForeignKey(CallSetupTime) field1 = models.FloatField() field2 = models.FloatField() mode = models.CharField(max_length=9, choices=test_modes) Form for Model_A is a simple ModelForm. Form for Model_B is also a ModelForm but with additional field: class Model_B_Form(forms.ModelForm): enable = forms.BooleanField(required=False, initial=True) class Meta: model = Model_B fields = ["field1", "field2", "mode"] widgets = {"mode": forms.HiddenInput()} The view for creating Model_A must contain also a formset for Model_B with four instances of Model_B's _modes. All four forms will be saved with parent_mdl pointing to the Model_A form's saved object: <html> <table> {{ model_a_form }} {% for form in formset %} <td>{{ form.enable }}</td> <td>{{ form.field1 }}</td> <td>{{ form.field2 }}</td> {% endfor %} </table> The FK Model_A will be supplied into .save method, and modes are passed as a list of initial data into the formset. The thing is that if the formset's single … -
Can't create user through POST request in Django
create user django post request I'm new in Django and DRF and I'm trying to create a new user through POST request. I send the username and password parameters but django doesn't identify the parameters inside the POST request. My serializer: class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) def create(self, validated_data): user=get_user_model().objects.create( username = validated_data['username'] ) user.set_password(validated_data['password']) user.save() return user class Meta: model = get_user_model() fields = ('username', 'password') My view class: class CreateUserView(CreateAPIView): model = get_user_model() permission_classes = (AllowAny,) serializer_class = UserSerializer I have tried to use serializers.ModelSerializer and serializer.Serializers but don't have success. -
Apache mod_wsgi error
I am trying to deploy a Django application to apache using mod_wsgi module with the following at the end of my /etc/apache/apache2.conf file ServerName localhost WSGIScriptAlias / /home/d_sehgal/Desktop/Bulk-Mailing-Solution/Bulk-Mailing-Solution/MailingSolution/MailingSolution WSGIPythonHome /usr/bin/python3 <Directory /home/d_sehgal/Desktop/Bulk-Mailing-Solution/Bulk-Mailing-Solution/MailingSolution/MailingSolution/> <Files wsgi.py> Order allow,deny Allow from all </Files> </Directory> WSGIDaemonProcess www.example.com python-home=/usr/bin/python3 python-path=/home/d_sehgal/Desktop/Bulk-Mailing-Solution/Bulk-Mailing-Solution/MailingSolution WSGIProcessGroup www.example.com Apache version info: root@divij-VirtualBox:/home/d_sehgal# apache2ctl -V Server version: Apache/2.4.18 (Ubuntu) Server built: 2016-07-14T12:32:26 Server's Module Magic Number: 20120211:52 Server loaded: APR 1.5.2, APR-UTIL 1.5.4 Compiled using: APR 1.5.2, APR-UTIL 1.5.4 Architecture: 64-bit Server MPM: event threaded: yes (fixed thread count) forked: yes (variable process count) Server compiled with.... -D APR_HAS_SENDFILE -D APR_HAS_MMAP -D APR_HAVE_IPV6 (IPv4-mapped addresses enabled) -D APR_USE_SYSVSEM_SERIALIZE -D APR_USE_PTHREAD_SERIALIZE -D SINGLE_LISTEN_UNSERIALIZED_ACCEPT -D APR_HAS_OTHER_CHILD -D AP_HAVE_RELIABLE_PIPED_LOGS -D DYNAMIC_MODULE_LIMIT=256 -D HTTPD_ROOT="/etc/apache2" -D SUEXEC_BIN="/usr/lib/apache2/suexec" -D DEFAULT_PIDLOG="/var/run/apache2.pid" -D DEFAULT_SCOREBOARD="logs/apache_runtime_status" -D DEFAULT_ERRORLOG="logs/error_log" -D AP_TYPES_CONFIG_FILE="mime.types" -D SERVER_CONFIG_FILE="apache2.conf" I have checked various answers and links but I cannot figure out what leads to this error. P.S. Newbie here. Any help is appreciated. -
POST data are not passed to the form in self.client.post of Django TestCase
I have a simple app which consists of textarea form to submit text via POST request. I started to write test cases and met a problem in passing data for the POST request in self.client.post. I followed this documentation. Here is my test case to check that the POST request with valid form data triggers successful redirection to the required link: class PostRequestTestCase(TestCase): def test_valid_post_request(self): '''post request with the valid form data should be successfully redirected and finish with status 200''' response = self.client.post('/', data={'text': 'foo'}), follow=True) self.assertEqual(response.redirect_chain[-1][1], 200) The problem here is that POST request does not send any data to my form and correspondingly this test fails with an error: Traceback (most recent call last): ... self.assertEqual(response.redirect_chain[-1][1], 200) IndexError: list index out of range Here is my code (simplified): html template # index.html <form method="post" enctype="multipart/form-data"> {{ TextInputForm.as_p }} <button type='submit'>Submit</button> </form> form # forms.py class TextInputForm(forms.Form): text = forms.CharField(widget=forms.Textarea, required = True) view # views.py def readtext(request): if request.method == 'GET': # form = TextInputForm() # elif request.method == 'POST': # form = TextInputForm(request.POST) # print('1: request.POST', request.POST) # if form.is_valid(): # print('2: Form is valid') # do stuff ... # return HttpResponseRedirect(reverse('do_stuff')) else: print('2: Form is … -
Django getting database fields with one query
I have a few models in django (User(standard), Member(extended user), Calculations, Subscription, Type) as follows : class Member(models.Model): user = models.ForeignKey(to=User) .......... class Calculations(models.Model): user = models.ForeignKey(to=User) ..... class Type(models.Model): limit = models.IntegerField() name = models.CharField(max_length=50) default = models.BooleanField() class Subscription(models.Model): started = models.DateField() type = models.ForeignKey(Type) member = models.OneToOneField(Member) Thus, Calculations is connected to User with ForeignKey Member is also connected to user with ForeignKey Subscriptions is connected to Member and with Type with ForeignKey In my view I want to query the database and to access information from all those models. Thus I want all members except the currently logged in, and I want to get the number of the calculations and the type of the subscription. I'm trying to do it with one query. I tried something like : @login_required def members(request): // That's how I get all information about user and members, but I also need the calculation and subscription members_list = Member.objects.select_related('user').all().exclude(user=request.user) context = {'members': members_list} return render(request, 'master/members.html', context) Any advice how can I do that? -
No module named installing Django App correctly
I've recently started a Django project using 1.10+ and it is not clear to me how to 'correctly' reference the app from the project settings without specifying the full path. I've read the Django Application Guide, but I'm still somewhat confused. Given the structure below, how do I 'install' the users app 'correctly so that it's reusable later on. This is my apps/user/app.py from django.apps import AppConfig class UserConfig(AppConfig): name = 'users' verbose_name = "User Catalogue" In settings.py for the project I would like to do the following... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # apps 'apps.users', ] I have also tried the following: apps.users.apps.UserConfig but get a No module named 'users' and even if it did work it's not as clean as using 'users'. -
how to pass json data into django forms and edit it and save it
I am calling an api and I am getting data in json form.Now I want to get some fields from json data in my django feils and make some changes there and save it back. -
django good style: copy built-in directory to local project?
This is somehow connected to my last question (django user with email as pk - hack possible?), but I try another approach: is it bad practice to copy the full django.contrib.auth to my project, and modify files there? I want to use a custom user model, and stumbled upon lots of things to change in permissions, groups, etc, besides the CustomUserManager and my CustomUser. Besides, I dont want to have groups in one app and MyUser in another. Besides, integrating userena needs some furher changes to User... Will this raise problems besides not being able to upgrade to next django version? Sorry for asking such an often-asked question, but somehow the manuals and forum posts are too diverse and contradicting to chose from... -
How to add objects to a table and be taken to another page? Django
If you have a look at the image, there's a table on the right where the selection of the user will be added to. When clicking on the "Compare Now" link the user will be taken to the comparison page. Essentially, how do i ADD the users selection to the table and query the db for those selections? -
Django: user.is_authenticated false after signup, allauth
I'm trying to set allauth up so that when a user successfully signs up they are redirected back to the page before they signed up and are automatically logged in. I've got the redirect working using a custom account adapter. However they are not logged in. Strangely allauth does add "Successfully signed in as X" to messages. Checking {% if request.user.is_authenticated %} in the template returns false, same for is_active. I need to go and manually log in. My settings for allauth are: ACCOUNT_AUTHENTICATION_METHOD = "username_email" ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = "optional" ACCOUNT_USERNAME_REQUIRED = True ACCOUNT_SIGNUP_FORM_CLASS = 'main.forms.SignupForm' LOGIN_REDIRECT_URL = '/' ACCOUNT_PRESERVE_USERNAME_CASING = True ACCOUNT_ADAPTER = 'main.adapters.MyAccountAdapter -
POST http://127.0.0.1:8001/maps/31/api/select/ 500 (INTERNAL SERVER ERROR)
I am working in Django. And using openlayer2 to create a polygon. Now I am sending it to server So I got this error. Can someone guide ? I have attached snapshot of response aswell. P.s I dont really know where is error. If you need anything tell me file name so I would post that here. -
Getting error while intstalling xhtml2pdf>=0.0.6 in django 3.6
I am trying to install xhtml2pdf>=0.0.6 and reportlab>=2.7,<3 for rendering PDF file but while installation getting below error:Microsoft Visual c++ 14.0 required.I f any one knows about this error please let me know Thanks in advance -
Django image (media) path don't display correctly in template
In my project i had set my media folder like this: settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py urlpatterns = [ .... ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) then in my models.py i create a class like this one: class PD_Pictures(models.Model): pic_IDmod = models.ForeignKey(PD_Models, related_name='modello') pic_image = models.ImageField() pic_descr = models.CharField(max_length=50) def __str__(self): return self.pic_descr at this point in my function in views.py i extract all values in db related to PD_Picture: prod_img = PD_Pictures.objects.all() ..... return render(request, 'base_catalog.html',{'bike_mod': bike_models,'prod_img': prod_img, 'cat_list': cat_list, 'menu_list': menu_list['menu'],'pcontent': menu_list['cont'], 'form': c_form}, context) and in my template, i would ti display related images: {% for pic in prod_img %} <div class="4u"><span class="image fit"><img src="{{ pic.pic_image }}" alt="" /></span></div> {% endfor %} well, at this point when i insert a new image in db, in table the path is 'newimage.jpg', fisically on my server the image was stored in '/media/newimage.jpg', how can i extract the value from the table and concatenate to the media path in my template? (/media/newimage.jpg) I had try to use 'upload_to='/models/' in my ImageField but the only effect is to save image into anoter model folder into main model. Thanks at all -
ModuleNotFoundError: No module named '__main__.models'; '__main__' is not a package
Currently working on a Django website and I'm having an issue importing a class and its attributes from my models.py module into my views.py module within my music app. From what I understand Django uses metaclasses to construct models, so the defined fields don't end up as attributes on the class. Is this the problem and if so how do I solve it? Directory Structure: music migrations templates _init_ admin.py apps.py models.py tests.py urls.py views.py The code inside models.py is: from django.db import models class Album(models.Model): artist = models.CharField(max_length=250) album_title = models.CharField(max_length=500) genre = models.CharField(max_length=100) album_logo = models.CharField(max_length=1000) def __str__(self): return self.album_title + ' - ' + self.artist The code inside views.py is: from django.http import HttpResponse from .models import Album from django.template import loader def index(request): all_albums = Album.object.all() template = loader.get_template('music/index.html') context = {'all albums': all_albums,} return HttpResponse(template.render(context, request)) def details(request, album_id): return HttpResponse("<h2> Details for Album id: " + str(album_id) + " </h2>") The Error: ModuleNotFoundError: No module named '__main__.models'; '__main__' is not a package Error Location: from .models import Album -
(Django)How to map two urls to one view?
This is my class: class Person(models.Model): name = models.CharField(max_length=64) persnr = models.AutoField(primary_key=True) This is my view: def show_person(request, persnr): pers = get_object_or_404(Person, pk=persnr) context={'pers':pers} return render(request, 'company/person.html', context) This is my url: url(r'^show_person/(?P<persnr>\d+)', "company.views.show_person", name='show_person'), How can I get to the same view (show_person) with these two urls: server/show_person/(persnr) server/show_person/(name) -
Django CSRF token is missing
I have an function in the custom.js file as follows : function contactTraxio(fullname, telephone, email) { if (typeof(fullname)==='undefined') fullname = null; if (typeof(telephone)==='undefined') telephone = null; if (typeof(email)==='undefined') email = null; bootbox.dialog({ title: "Limit reached", message: '<p class="text-main text-center">You have reached the limit of your calculations.</p>' + '<p class="pad-btm mar-btm text-center">Upgrade your account by contacting us on +32 9 111 12 12 or filling in the form below.</p>' + '<div class="row"> ' + '<div class="col-md-12"> ' + '<form class="" method="POST"> ' + '<div class="form-group"> ' + '<div class="col-md-6" style="padding-left: 0"> ' + '<input id="contact-fullname" name="fullname" type="text" placeholder="Your fullname" class="form-control input-md" value="' + fullname + '"> ' + '<span class="help-block"><small></small></span> </div> ' + '</div> ' + '<div class="col-md-6" style="padding-right: 0"> ' + '<input id="contact-telephone" name="telephone" type="text" placeholder="Telephone" class="form-control input-md" value="' + telephone + '"> ' + '<span class="help-block"><small></small></span> </div> ' + '</div> ' + '<div class="col-md-12 pad-no-lr-md" style="margin-top: 7.5px;"> ' + '<input id="contact-email" name="email" type="text" placeholder="Your email address" class="form-control input-md" value="' + email + '"> ' + '<span class="help-block"><small></small></span> </div> ' + '</div> ' + '</div>' + '</form> ' + '</div>' + '</div>', buttons: { success: { label: "Send", className: "btn-primary", callback: function () { $.ajax({ type: 'POST', url: '/master/contact_traxio/', data: … -
Path of the file location before submiting
I am doing a new django project.and I want to know actual path of the file. using forms and views I upload a file into but before click the submit button I need to know the actual path(/home/anson/sampleout/arun/arun.txt).How I get this path. Please give me a solution. Thnaks in advance -
%endwith% before %empty% (in Django template)
Need to clarify a quick concept. Experimenting within a Django template, I have found that this is legit: {% for object in object_list %} {% with forms|get_item:object.id as replyform %} {% endwith %} {% empty %} Sorry, the object list is empty! {% endfor %} Whereas, the following gives me a TemplateSyntaxError error (Invalid block tag: 'empty', expected 'endwith'): {% for object in object_list %} {% with forms|get_item:object.id as replyform %} {% empty %} Sorry, the object list is empty! {% endwith %} {% endfor %} What's the reasoning behind the latter being legit, and not the former? Don't exactly see anything regarding this in the docs. -
populating a django form dynamically with the data
I have a django view as follows: @login_required(login_url="login/") def review(request): table = DummyTable(DummyModel.objects.all()) form = DummyForm() return render(request, 'review.html', {'reviews': table, 'DummyForm': form}) I am passing a default DummyForm which is a django-crispy-form (although this does not matter to the issue, I think) and I need to populate it depending on the record that the user clicks on. The form itself looks as: from .models import DummyModel from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Field, ButtonHolder, Submit from django.forms import ModelForm class DummyForm(ModelForm): class Meta: model = DummyModel fields = ['name', 'description', 'time_points'] def __init__(self, *args, **kwargs): super(DummyForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-sm-2' self.helper.field_class = 'col-sm-10' self.helper.layout = Layout( Field('name'), Field('description'), Field('time_points'), ButtonHolder( Submit('submit', 'Submit', css_class='button white') )) Now, I have a javascript function that gets called when the user clicks on certain links and receives the primary key for the record that I want to render in the form. Currently, it is as follows: <script> function EditDialog(pk) { // Currently doing nothing with the primary key $( "#dialog" ).modal({width: 500, height: 500}); return false; } </script> This JS function initiates the form as: <div id="dialog" class="modal" title="Edit" style="display:none"> <div class="modal-dialog"> <div class="modal-content"> … -
Wagtail feed_image not Displaying on Index Page
I cannot seem to figure out why my feed_image works on the page when called as {{ self.feed_image }} but when trying to add to the index page, it will not display - just shows a broken image. snippet @register.inclusion_tag( 'tags/_product-snippets.html', takes_context=True ) def product_snippets(context, calling_page): pages = calling_page.get_children().live() return { 'pages': pages, # required by the pageurl tag that we want to use within this template 'request': context['request'], } tag <div class="row"> {% for page in pages %} <div class="col-md-3 col-sm-4 col-xs-12"> <div class="shop-item-container-in"> {% image page.feed_image as img %} <img src="{{ img.url }}" alt="{{ page.title }}" title="{{ page.title }}" class="img-responsive center-block shop-item-img-list-view"/> </div> <h4><a href="{% pageurl page %}">{{ page.title }}</a></h4> <a href="{% pageurl page %}" class="button button-md button-pasific hover-icon-wobble-horizontal mt25">More<i class="fa fa-shopping-basket"></i></a> </div> {% endfor %} </div> html ... {% product_snippets calling_page=self %} ...