Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why safari reload the page when I swipe back on ios?
I'm doing a webpage with Django. When i want to test the proyect on safari ios y try to use the swipe back or the button back but doesn't the right action, but reload the same page. I test the same swipe in another webpage and works correctly. Does anyone know why it happens and how to correct it? -
How to perform reverse relation in django?
This is my models: class journal(models.Model): Date = models.DateField() By = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='Debitledgers') To = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='Creditledgers') Debit = models.DecimalField(max_digits=10,decimal_places=2) Credit = models.DecimalField(max_digits=10,decimal_places=2) class Selectdate(models.Model): Journal = models.ForeignKey(journal,on_delete=models.CASCADE,null=True,blank=True,related_name='journals') Start_Date = models.DateField(default=datetime.date(2018,4,1),blank=False) End_Date = models.DateField(default=datetime.date(2019,3,31),blank=False) I want to filter the journal objects within the "Start_Date" and "End_Date" of the Selectdate model... This might me a stupid question to ask...But, as I am learning django, its not easy for me... Can anyone tell me how to do this??? Thank you in advance -
hstore or jsonb for model specific settings
I have a model called Student. Students can have a lot of specific settings for which I don't want to create extra fields like: preferred_color gender etc. I don't need nested settings and I wonder what is the better solution for this situation? -
Loading initial pages in data migration (wagtail)
I'm new to Django and Wagtail and trying to set my CMS up to load with the minimum set of pages for our nav to function correctly. The short problem is that objects extending Wagtail's Page type are not loading, though the data migration appears to succeed. In my case I have a bunch of Organizations & OrganizationTypes (extending BasicObject), as well as some Page objects: OrganizationIndexPages OrganizationPages. I've dumped the data using the standard dumpdata command and have it, including all pages, in an initial_data.json file and am loading it using a data migration similar to the accepted answer here. The problem is that I get all my Organizations and OrganizationTypes, but no Page objects after re-migrating. I even added some printing to the output to verify: ``` loaded <DeserializedObject: orgs.Organization(pk=19)> loaded <DeserializedObject: orgs.Organization(pk=20)> loaded <DeserializedObject: orgs.OrganizationType(pk=1)> loaded <DeserializedObject: orgs.OrganizationType(pk=2)> loaded <DeserializedObject: orgs.OrganizationType(pk=3)> loaded <DeserializedObject: orgs.OrganizationPage(pk=7)> loaded <DeserializedObject: orgs.OrganizationPage(pk=8)> loaded <DeserializedObject: orgs.OrganizationPage(pk=10)> ``` -
Django export data to csv file with CBV
I'm looking for export data from database to different files formats (.csv, .json, .xls ...). The idea should be : user go to a new template and can access to many download buttons. When it clicks on one, he downloads the file with the choosen format. I have this view : class Exports(ListView): template_name = 'exports.html' context_object_name = 'exports' def export_categories_csv(request): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="categories.csv"' writer = csv.writer(response) writer.writerow(['id', 'name']) categories = Category.objects.all().values_list('id', 'name') for category in categories: writer.writerow(category) return response def get_context_data(self, **kwargs): self.export_categories_csv() return super(HomeView, self).get_context_data(**kwargs) My urls.py file looks like this : url(r'^exports$', Exports.as_view(), name='exports'), And the associated template : {% load staticfiles %} {% load i18n %} {% block main %} <a href="{% url 'exports' %}" class="btn btn-default">Export all categories in CSV</a> {% endblock main %} How I can create different buttons and display these buttons in the same page ? And how I can make the links between each button and each functions inside the same class. Up to now, the issue is : Exports is missing a QuerySet. Define Exports.model, Exports.queryset, or override Exports.get_queryset(). -
Prepopulate edit form fields with database data
First of all i want to say that I'm new to Django, but I'm enjoying it alot. Atm I am trying to make a kinda simple bank account management website. I've done the registration, views, user restrictions (logged, anonymous user), user customization(password change, edit profile informations). And I stopped on the last one. The problem is that whenever I'm on the edit-profile url, the edit profile form (EditProfileForm) doesn't display the currently field values in the input boxes Edit Profile As you see, the fields are empty although there's values in database (I can check with the admin-page or my custom ProfileView) models.py class UserProfile(models.Model): username_validator = UnicodeUsernameValidator() username = models.CharField(_('username'), max_length=20, unique=True, help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'), validators=[username_validator], error_messages={ 'unique': _("A user with that username already exists."), },) password = models.CharField(_('password'), max_length=128, default='') first_name = models.CharField(_('first name'), max_length=30) last_name = models.CharField(_('last name'), max_length=150) email = models.EmailField(_('email address')) card_nr = models.CharField(max_length=16, default='') location = models.CharField(choices=CHOISE_LOCATIONS, max_length=20, default='') phone_number = models.CharField(_('phone number'), max_length=10, default='') bank_account = models.CharField(_('bank account'), max_length=20, default='') EMAIL_FIELD = 'email' USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] def __str__(self): return self.username def create_profile(sender, **kwargs): if kwargs['created']: user_profile = UserProfile.objects.create(username=kwargs['instance']) post_save.connect(create_profile, sender=User) forms.py class EditProfileForm(forms.ModelForm): β¦ -
Django rest framework POST data w/ username in the background
The idea is whenever user posts a product, it saves product name and price + saves user object(i.e request.user) At this moment I have an error IntegrityError at /api/product/ null value in column "ordered_by_id" violates not-null constraint and im not sure what to do to save user instance in the background my models.py class Product(models.Model): price = models.FloatField() name = models.CharField(default='Gift',max_length=512) ordered_by = models.OneToOneField(User, null=False, unique=False) date = models.DateField(auto_now_add=True) purchased = models.BooleanField(default=False) my serializers.py class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ( "price", "name", ) my views.py class ProductList(generics.ListCreateAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer def pre_save(self, obj): obj.ordered_by = self.request.user -
Render slow loading results
I have a website that uses a pretty slow external API (0.9 seconds for a request). The results from this API request are rendered to the page. I use some kind of own caching, because I store the results in a DB and subsequent queries for the same resource are queried from the DB rather than requesting from the API again. If the data in the DB is too old (>10 Minutes), I update the DB with a new API request. It will be pretty common to check the website only occasionally during the day, so you will always hit the 10 Minute limit and always have a pretty long loading time >1s. This feels very unresponsive. I then searched for ways to get around the loading time and found this. I think this could be the right direction, but I am still not confident on how to tackle the task. Can anybody point me in the right direction as how to implement this? Should I use the low level cache api? Could I use the default cache? Or should I implement my own version? Do you think the solution provided in the first link is a good idea at β¦ -
Sent update to client about progress of a long running task from view
I have a page on my website where user can upload a xlsx file using ajax, on backend I read the file, do a little processing and start inserting its rows one by one in my database. If the files uploaded by the user gets quite large, entering new values in the database can take a while. Therefore I want to give user real-time progress update on their screen, eg. - Found 100 rows of data Interesting 1/100. Interesting 2/100. ... Interesting 100/100. Done. My View: import pandas as pd def myView(self, request): """Handle POST requests, save all data provided in excel file.""" excel_file = request.FILES.get('excel_one') excel_df = pd.read_excel(excel_file) data_format = ['Option_1', 'Option_2', 'Option_3', 'Option_4',] try: formatted_df = excel_df[data_format] except KeyError as error: return JsonResponse({'success': False, 'message': str(error), }) # forloop to create model objects for i, v in formatted_df.iterrows(): MyModels.objects.create(arguments) print(f'Created object {i+1}/{len(formatted_df)}!' # Want to to be sent to html page in real time return JsonResponse({'success': True, }) I am making an ajax request like this: $.ajax({ // variables url, data, etc. contain the expected stuff async: false, url: url, method: "POST", data: data, success: function(d){ if(data.success){ console.log(d); } else{ $('.log').append('<p><b>Error:</b> '+ d.message +'</p>') } }, cache: false, β¦ -
Django + webpack + reactjs: how to generate multiple pages by separate reactjs code for each url
I am trying to follow: https://medium.com/uva-mobile-devhub/set-up-react-in-your-django-project-with-webpack-4fe1f8455396 for webpack + django + reactjs with the below directory structure repodirectory/ βββ mysite/ β βββ mysite/ # project β βββ polls/ # app β βββ static/ β βββ bundles/ # generated by webpack β βββ js/ β βββ templates/ β βββ polls/ # generated by webpack β βββ index.html/ β βββ questions.html/ β βββ manage.py β βββ webpack-stats.json # generated by webpack βββ .babelrc βββ package.json βββ webpack.config.js βββ node_modules/ #contains our JS dependencies I have two urls: http://127.0.0.1:8000/polls/ -- uses index.html template http://127.0.0.1:8000/polls/questions/ -- uses questions.html template but i have only index.js in which i write the reactjs code So how to write separate reactjs code for each url and then bundle it using webpack -
Load json file in Django
Currently, I am using code below to load data.json file: $.getJSON("http://127.0.0.1:8000/data.json", function(data) { However, there is always an error like this: "GET http://127.0.0.1:8000/data.json 404 (Not Found)". File stru The data.json file is under the directory where my home.html locates. -
django - Records not saved in MySQL database but AutoIncrement gets increased
I'm facing a weird one here. I'm using django inside a docker container. When the system tries to save some records (mostly it works!) they don't end up in the database. When I view the process in the debugger, the django objects gets saved, it gets an ID from the database and inside the django world everything seems fine. But the record never shows up in the database! Even weirder: If I look at the table's meta options I see that per record which should have been created the AutoIncrement is increased. So it appears the database knows about the records but dedides not so save them... I tried it on my Windows machine, the server runs UNIX, both have the same issue. I'm using django==2.0.9 and mysqlclient==1.3.13. When I switch the table engine from InnoDB to MyISAM then it works. Reproducibly it happens for the django-axes tables but I experienced the issue in other parts of the system as well. The calls come via the django-restframework to django. Frankly I have no idea where to start looking for the issue. 1) On Windows and (server's) UNIX it occurs, on another's developers UNIX, it works 2) I downgraded latest mysqlclient, β¦ -
Exclude related objects before Count
For example I've got 3 models User, A, B. class A(models.Model): creator = models.ForeignKey( 'users.User', on_delete=models.CASCADE, related_name='A_set' ) class B(models.Model): user = models.ForeignKey( 'users.User', on_delete=models.CASCADE, related_name='B_set' ) a_model = models.ForeignKey( 'a.A', on_delete=models.CASCADE, related_name='B_set' ) I would like to get count of B where user isn't a creator of a_model object. I've tried query: `User.objects.prefetch_related('B_set').last().B_set.exclude(a_model__creator=F('user')).count()` Here is my try with annotation: User.objects.annotate(b_count=Count('B_set', filter=(~Q(B_set__A__creator=F('user'))))) But I am getting an error: Cannot resolve keyword 'user' into field. And then it suggest me fields that relate to User. Also I tried to change user to B_set__user with F() but it didn't help. -
Centos 7 - Apache Dont restart - Permission Denied
I work on Centos 7 with an Django Web Project. A few months ago with an old version of my website everything works great. But after a restart of the server cluster (few days) and the implementation of the new code of the website(today), i have got this error.... My error is when i want restart the httpd service with : sudo systemctl restart httpd I got this error : β httpd.service - The Apache HTTP Server Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled) Active: failed (Result: exit-code) since mar. 2018-10-09 14:20:19 CEST; 8s ago Docs: man:httpd(8) man:apachectl(8) Process: 398981 ExecStop=/bin/kill -WINCH ${MAINPID} (code=exited, status=1/FAILURE) Process: 398979 ExecStart=/usr/sbin/httpd $OPTIONS -DFOREGROUND (code=exited, status=1/FAILURE) Main PID: 398979 (code=exited, status=1/FAILURE) oct. 09 14:20:18 web01 systemd[1]: Starting The Apache HTTP Server... oct. 09 14:20:19 web01 httpd[398979]: httpd: Syntax error on line 99 of /etc/httpd/conf/httpd.conf: Syntax error on line 1 of /etc/httpd/conf/vhosts_django.conf: Cannot load /mnt/storage/venv-site-python3.6/lib/python3.6/site-packages/mod_wsgi/server/mod_wsgi-py36.cpython-36m-x86_64-linux-gnu.so into server: /mnt/storage/venv-site-python3.6/lib/python3.6/site-packages/mod_wsgi/server/mod_wsgi-py36.cpython-36m-x86_64-linux-gnu.so: failed to map segment from shared object: Permission denied oct. 09 14:20:19 web01 systemd[1]: httpd.service: main process exited, code=exited, status=1/FAILURE oct. 09 14:20:19 web01 kill[398981]: kill: cannot find process "" oct. 09 14:20:19 web01 systemd[1]: httpd.service: control process exited, code=exited status=1 oct. 09 14:20:19 web01 systemd[1]: Failed β¦ -
Django: earliest() and latest() require either fields as positional arguments or 'get_latest_by' in the model's Meta
Can Anyone please explain me what this error means?? I have done this in my views.py: class FormListView(FormMixin, ListView): def get(self, request, *args, **kwargs): # From ProcessFormMixin form_class = self.get_form_class() self.form = self.get_form(form_class) # From BaseListView self.object_list = self.get_queryset() allow_empty = self.get_allow_empty() if not allow_empty and len(self.object_list) == 0: raise Http404(_(u"Empty list and '%(class_name)s.allow_empty' is False.") % {'class_name': self.__class__.__name__}) context = self.get_context_data(object_list=self.object_list, form=self.form) return self.render_to_response(context) def post(self, request, *args, **kwargs): return self.get(request, *args, **kwargs) class CompanyListView(LoginRequiredMixin,FormListView): model = Company form_class = daterangeform paginate_by = 10 def get_queryset(self): return company.objects.filter(User=self.request.user) def get_context_data(self, **kwargs): context = super(companyListView, self).get_context_data(**kwargs) context['selectdate_list'] = selectdate.objects.filter(User=self.request.user).latest() return context And I am getting this error: ValueError: earliest() and latest() require either fields as positional arguments or 'get_latest_by' in the model's Meta. Can anyone please explain me what is wrong in my code and possible solution for doing it in correct way... Thank you -
Unknown request URI: /datastore
I am using cloud datastore with my django 2.1 application. When I enter the localhost:8081, it gets me to the page saying ok. But when I type localhost:8081/datastore, it gives me following error. [datastore] INFO: Unknown request URI: /datastore I am using datastore emulator. Please help. -
Use query result from many to many relations to sort list in django admin
Here's what my Admin class looks like class GuestAdmin(admin.ModelAdmin): inlines = (GuestEpisodeAdmin, TopicGuestAdmin, JobGuestAdmin) exclude = ('episodes', ) list_display = ('name', 'twitter', 'gender', 'medium', 'appearance_count', 'last_appearance') list_filter = ['gender'] search_fields = ['name', 'twitter', 'bio', 'notes'] def get_queryset(self, request): qs = super(GuestAdmin, self).get_queryset(request) qs = qs.annotate( _appearance_count=Count('episodes') ) return qs def appearance_count(self, obj): return obj._appearance_count def last_appearance(self, obj): la = obj.episodes.order_by('-published_at').values_list('published_at', flat=True).all().first() if isinstance(la, datetime.datetime): la = la.strftime("%Y-%m-%d") return la # last_appearance.admin_order_field = 'last_appearance' appearance_count.admin_order_field = '_appearance_count' So the last_appearance comes from the episodes connected to the guest (many-to-many relationship) by using the publish date from the newest episode. My goal is to have them sortable in the list view on django admin. I learned that I can't get this into the get_querysetbut i'm sure there is a way. I couldn't find one yet. -
django_comments site package missing templates?
I am moving a website from my local dev machine to PA. I'm getting a template not found error. After a bit of searching, it appears that it is not finding the django_comments form.html template in the templates directory. Presumably, because of this, collectstatic isn't creating the static file to serve. Looking at the install on my dev machine, there is a template directory in the site-package but not in the package on PA. I notice that my django.contrib_comments distro is 1.9.0 while it is 1.8.0 on PA. (artifact of my venv creation?) My question is "am I missing something". I can certainly get around the problem by including the templates in my own directory, but for obvious reasons, I'd rather not. Suggestions? (if I run pip install, I'm getting a unicode not defined error) Thx, --Don -
Modelformset with Django's formwizard
I can't seem to find a good answer for my question. I have created a formwizard using SessionWizardView and I want to present multiple modelforms in 1 step of the wizard. I am trying to implement a modelformset. From my reading, some have suggested overriding the get_form_instance and inserting the modelformset via context this way but I can't seem to figure it out. Can you point me in the ride direction? Any help would be much appreciated? -
Django: Refreshing page resubmits form.
I am facing one weird issue while using Django. I can see two entry of the video I am submitting in the database as the page where I am submitting the form refreshes automatically after submission (that is okay to refresh, as I can see the updated results in the table). But the problem is while refreshing it resubmits the form. And if I manually refresh the page also it keeps submitting new videos. After doing some research I've found articles which leads to the problem in views.py in the application. There is a similar question as well but the way they did I am not sure how to integrate with my view as I am returning some args to the page too. (Reference article: django form resubmitted upon refresh) Below is the code which I already understand less. # Uploading videos form if not request.method == "POST": f = UploadForm() # Send empty form if not a POST method args = {"profile_data": profile_data, "video_data": video_data, "form": f} return render(request, "home.html", args) f = UploadForm(request.POST, request.FILES) # This line is to upload the actual user's content. if not f.is_valid(): # Q: Why do we need to check this? And if β¦ -
Why was json sent to email? [on hold]
I am using Django's django.core.mail. I wrote codes made document of docx and send it by using email. I wrote, def app(): id = str(uuid.uuid4()) document.save(f"{id}.docx") result = {"id": id} result_str = json.dumps(result, ensure_ascii=False, indent=2) mail(email, result_str) return render(request, 'email.html') def mail(email, docx): subject = "send email" message = "testtest" from_email = settings.EMAIL_HOST_USER recipient_list = [ email ] message = EmailMessage(subject, message, from_email=from_email, to=recipient_list) message.attach(docx, 'contents', 'application/json; charset=UTF-8') message.send() I called app's method,but in that time json was sent by email.In local,docx was saved,so I really cannot understand why such a thing happens.What is wrong in my codes?How should I fix this? -
ModuleNotFoundError: No module named 'bootstrap3'
I've installed Anaconda and python 3 on it. next I've installed django and django-bootstrap3. it's shown in pip freeze and it is in C:\Users\Asus\Anaconda3\Lib\site-packages folder. but when i run my project this error appears: ModuleNotFoundError: No module named 'bootstrap3' why it doesn't know bootstrap 3? -
Django ticket system
Get actual/active waiting number returns: - 1245, 2017-09-01 15:22, 0 After deletion of the last active number the list looks as follows: - 1246, 2017-09-01 15:42, 0 - 1250, 2017-09-01 16:32, 1 - 1251, 2017-09-01 19:20, 2 I am completely new to stack-overflow, sorry for typos -
#Python #Django, how to join sub directory of media_root base directory
i am trying to join the sub directory of media_root base directory to uploads files under sub directories the idea behind is every each user have his owner directory which is containing all his files uploaded here is my code mySubDir = "REAGAN" #my media_root base directory userDir = settings.MEDIA_ROOT joinedDir = os.path.join('{userDir}'.format(userDir=userDir)) #now under the "joindDir" variable i want join my mySubDir which i defined on top then i can uploads my files under that directories full code in function def getFilePath(instance, filepath): baseName = os.path.basename(filepath) baseExtension = os.path.splitext(filepath)[1] mediaTv = ['.mov','.wmv','.mpeg','.mpg','.avi','.rm', '.mp4'] mediaRadio = ['.mp3','.m4a','.wav','.aiff','.midi','.m4p' '.ogg'] mediaPrint = ['.jpg','.jpeg','.gif','.png','.tif','.tiff'] if User.is_authenticated: userDir = settings.MEDIA_ROOT joinedDir = os.path.join('{userDir}'.format(userDir=userDir)) userDir = os.path.join('/dallas') #the directorie i want joined if baseExtension in mediaPrint: fullPath = '{baseName}{baseExtension}'.format(baseName=baseName, baseExtension=baseExtension) _dirTypes = 'Print/{fullPath}'.format(fullPath=fullPath) getOS = os.path.join('{joinedDir}'.format(joinedDir=joinedDir), _dirTypes) #i need join it here return getOS else: print('oops something went wrong') -
generating pdf using easyprint in django
i am trying to generate a pdf from a html template using easyprint in django but some of the css is not rendering when page break occurs.even writing-mode: vertical-rl; css property is not working. im rendering dynamic json data to the html template to convert it as pdf using easyprint. when table breaks and go to the next page some css won't renter in the next page. enter code here @register.simple_tag def displayRetirementPlanningAnalysisView(object_lists, object_lists2): ob = object_lists ln = len(ob) ob2 = object_lists2 ln2 = str(len(ob2) + ln + 1) htmltable = '' if len(object_lists) > 0: htmltable += '<THEAD>' htmltable += '<tr>' htmltable += '<th class="emptyheading">' + '</th>' htmltable += '<th class="tableHeadingData" >' + 'Particulars(Pre-Retirement)' + '</th>' htmltable += '<th class="text-right">' + 'Value' + '</th>' htmltable += '</tr>' htmltable += '<tr>' htmltable += '<td class=" sideHeading" rowspan="' + ln2 + '">' htmltable += '<div class="labelSection" >Retirement Planning Analysis</div></td>' for obj in object_lists: htmltable += '<tr>' htmltable += '<td class="particularsLabels" >' + str(obj.get('particular')) + '</td>' htmltable += '<td class="text-right td-font" >' + str(obj.get('value')) + '</td></tr>' htmltable += '<tr><th class="tableHeadingData" >' + 'Particulars(Post-Retirement)' + '</th>' htmltable += '<th class="text-right">' + 'Value' + '</th></tr>' for obj1 in object_lists2: htmltable += '<tr>' htmltable β¦