Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Circular import with multiple files
I have 3 python files within a package, I'm trying to import a class from one file into other 2 file. But i get error. models __init__.py a.py b.py c.py a.py class ATestOne() pass class ATestTwo() pass class ATestThree() pass b.py from app.models.a import ATestOne, ATestTwo from app.models.c import CTestOne class BTestOne() field1 = models.ForeignKey(ATestOne) class BTestTwo() field1 = models.ForeignKey(CTestOne) c.py from app.models.a import ATestOne, ATestThree from app.models.b import BTestOne class CTestOne() field1 = models.ForeignKey(ATestOne) class CTestTwo() field1 = models.ForeignKey(BTestOne) Returns below mentioned error ImportError: cannot import name 'ATestOne' Kindly advice in solving this. Thanks in advance. -
To get the weight of product in ebay api
Currenly i am working in ebaysdk. I am facing the problem which is the weight of the product. how can i can get product weight ? I used trading api but most of weight of the products equal to 0. is there any way to get product weight all the time? I requested like this: response = api_trading.execute('GetItem' , {"ItemID":"184097524395",'DestinationPostalCode':'2940','DestinationCountryCode':'GB'}) -
pip install mysqlclient returns Building wheel for mysqlclient (setup.py) ... error
[its show wheel error and fatal error error that cannot open file mysql.h pip install mysqlclient returns Building wheel for mysqlclient (setup.py) ... error] -
How to return multiple fields from a Model object?
I am doing testing in django and already created a model instance using ddf.G. Now I want to use this instance in a test case to return multiple fields of the model. I know how to return multiple fields using queryset like: model_values = models.User.objects.values_list( 'first_name', 'last_name', 'image__name', 'image__description' ) Now I want to return same fields but by using the instance I already have. Is there any way to achieve this? -
Django Storage app, different "upload_to" depending on user's choice
I'm trying to implement functionality where user can upload file and choose (in the form) if this file is going to be global (available for everybody) or private (available only for him). The form would look like this Firstly I have doubled model, view, form etc. where only difference was: file = models.FileField(upload_to=user_directory_path) and file = models.FileField(upload_to='global files/') what destroys DRY rule. Obviously it's not what I want to achieve. So then I tried to make a boolean in model and change "upload_to" parameter depending on user's choice: title = models.CharField(max_length=50, blank=True) uploaded_at = models.DateTimeField(auto_now_add=True) file = models.FileField(upload_to=user_directory_path) user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) STATUS = ( (1, ('Global file')), (2, ('My file')), ) status = models.CharField(max_length = 30, choices=STATUS, default=2) if status == 'My file': file = models.FileField(upload_to=user_directory_path) elif status == 'Global file': file = models.FileField(upload_to='global files') Unfortunately it doesn't work. Does anyone has any idea how to implement that? -
An out of my knowledge error while executing a python script
I wrote a python script to populate my database with some fake data using the Faker library for a casual project as i am learning Django. My project name is "ProTwo" and there is an application inside of this project named "apptwo". This is the python script i wrote: (populate_users.py) import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", 'ProTwo.settings') import django django.setup() from apptwo.models import User from faker import Faker fakegen = Faker() def populate(N=5): for entry in range(N): fake_name = fakegen.name().split() fake_first_name = fake_name[0] fake_last_name = fake_name[1] fake_email = fakegen.email() user = User.objects.get_or_create(first_name = fake_first_name, last_name = fake_last_name, email = fake_email)[0] user.save() if __name__ == '__main__': print('POPULATING DATABASES!') populate(20) print('POPULATION DONE!') models.py: from django.db import models class User(models.Model): first_name = models.CharField(max_length = 264,null = True) last_name = models.CharField(max_length = 264, null = True) email = models.EmailField(max_length=254, unique = True) (views.py): from django.shortcuts import render from django.http import HttpResponse from apptwo.models import User def index(request): return render(request,'app_two/index.html') def users(request): user_list = User.objects.order_by('first_name') user_dict = {'users': user_list} return render(request,'app_two/users.html', context = user_dict) (urls.py): from django.contrib import admin from django.conf.urls import url, include from apptwo import views urlpatterns = [ url(r'^$',views.index, name = 'index'), url('admin/', admin.site.urls), url(r'^users/', include('apptwo.urls')), ] and this is the error on executing the … -
React app with Django error 'string indices must be integers'
I have a react app with Django Rest framework. Here is the folder structure where "api" is the app for rest API and "frontend" is an app for React App. here is code of frontend/urls.py urlpatterns = [ #path('', views.index), #url(r'^(?:.*)/?$', views.index), url(r'^.*$', TemplateView.as_view(template_name="frontend/index.html")),] Here is relevant part webpack.config.json const PATHS = { app: path.join(__dirname, "src"), template: path.join(__dirname, "templates/frontend"), build: path.join(__dirname, "static/frontend")};const productionConfig = merge([ parts.output({ path: PATHS.build, publicPath: '/frontend/' }), parts.extractStyles({ use: ["css-loader", "sass-loader", parts.autoPrefixer()] }), parts.minifyJs(), parts.minifyStyles({ options: { discardComments: { removeAll: true, }, // Run cssnano in safe mode to avoid // potentially unsafe transformations. safe: true, }, }), parts.bundleTracker({ filename: '../../../webpack-stats.json' }),]); Below is created webpack-stats.json {"status":"done","chunks":{"main":["vendor.css","vendor.js","main.css","main.js"]},"publicPath":"/frontend/","assets":{"main.css":{"name":"main.css","path":"E:\\freelance\\familytree\\frontend\\static\\frontend\\main.css","publicPath":"/frontend/main.css"},"main.js":{"name":"main.js","path":"E:\\freelance\\familytree\\frontend\\static\\frontend\\main.js","publicPath":"/frontend/main.js"},"vendor.css":{"name":"vendor.css","path":"E:\\freelance\\familytree\\frontend\\static\\frontend\\vendor.css","publicPath":"/frontend/vendor.css"},"vendor.js":{"name":"vendor.js","path":"E:\\freelance\\familytree\\frontend\\static\\frontend\\vendor.js","publicPath":"/frontend/vendor.js"},"vendor.js.LICENSE.txt":{"name":"vendor.js.LICENSE.txt","path":"E:\\freelance\\familytree\\frontend\\static\\frontend\\vendor.js.LICENSE.txt","publicPath":"/frontend/vendor.js.LICENSE.txt"},"index.html":{"name":"index.html","path":"E:\\freelance\\familytree\\frontend\\static\\frontend\\index.html","publicPath":"/frontend/index.html"}}}} When I run the application, I see below error. -
How to implement in-app purchase server to server notification in django or node js?
I am trying to implement in-app purchase server to server notification. Can anyone help me how to implement? -
Use Admin List Actions to Create New Object
I have a model with Email_address and Email_message, connected with a many-to-many relationship. Email_message.email_addresses refers to the recipients of the Email_message. models.py class Email_address(models.Model): address = models.EmailField() contact_name = models.CharField(max_length=50, null=True, blank=True) class Email_message(models.Model): email_addresses = models.ManyToManyField(Email_address, related_name='email_messages') subject = models.CharField(max_length=50) body = models.TextField() date_time = models.DateTimeField(null=True, blank=True) I would like to select many Email_address objects through the list view in Admin, then use an action to create a new Email_message. All of the selected Email_address objects would be saved as recipients. What is the simplest way to do this? I've thought about creating forms in a new template but it seems overly complicated. It should be possible to pass the email_address action's queryset to Django Admin's default add new email_message page but I can't figure out how this could be done. So again, what is the cleanest way to do this? -
How can i send real time data to a client on Django?
On a server, i'm hosting a Python script that streams some JSON data received by a lot of IoT sensors. I'm trying to find a way to have that data on a Django application: if the user opens the page for sensor 30, the user must get real time data from sensor number 30 and so on. I know that Django Channels is the standard to hadle real time data on Django, but in this case the data is not generated by the client and its not generated by Django Channels, the user only needs to receive the data. Using a database is out of question due to performances and because i don't need to store any data at all. Is there a way to do this? I was thinking of creating a websocket on my data generator script (using SocketIO maybe?), for every sensor i would create a room, while on my Django frontend i would add some Javascript to connect to the websocket server and to that sensor's room. So user opens the page for sensor 35, the frontend will connect it to my external websocket server and then to the room of that sensor. I know this … -
Django displaying the value of changed field
I am building my first Django website as a post office that can track items in a database. However, I am having problem displaying the location history of a tracked package. I tried using simple history but it does not look at a value of a field while fieldtracker only works on my local shell environment. Every time I restart my shell, the history is gone and it does not work on the whole database itself. My package model class Packages(models.Model): package_ID = models.IntegerField(primary_key=True) package_description = models.CharField(max_length=100,default="None") weight = models.DecimalField(max_digits=5,decimal_places=2) signature = models.BooleanField(default=False) delivery_status = models.BooleanField(default=False) order_date = models.DateField('Date Sent') sent_by = models.ForeignKey(Sender,on_delete=models.CASCADE) sent_to = models.ForeignKey(reciever,on_delete=models.CASCADE) tracker = FieldTracker() def __str(self): return self.package_ID My package_history model class package_history(models.Model): package_ID = models.ForeignKey(Packages,on_delete=models.CASCADE) current_location = models.ForeignKey(branches,on_delete=models.CASCADE) def __str(self): return self.package Please if anyone have any idea on how to tackle this it would be greatly appreciated. Thank you -
Chartjs and django - mutiple datasets issue
Having an issue with my chart whereby i can only render 1 dataset in my line chart. I think the issue is with my views because if i hardcode the values in my html directly, everything works. "views.py" def get(request, *args, **kwargs): return render(request, 'dashboard.html', {}) data1 = [28, 89, 50, 94, 45, 67, 78] data2 = [34, 100, 234, 79, 156, 123, 76] class ChartData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None): label1 = ['0s', '10s', '20', '30s', '40s', '50s', '60s'] data = { "labels": label1, "default1": data1, "default2": data2, } return Response(data) "ursl.py" from django.urls import path from . import views from django.contrib.auth import views as auth_views urlpatterns = [ path('data/', views.get, name='data'), path('snmp/', views.ChartData.as_view(), name='snmp'), ] "html code" <script src="https://code.jquery.com/jquery-3.4.1.js"></script> <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script> <canvas id="myChart" width="500" height="500"></canvas> <script> var endpoint ='/snmp/' var defaultDatas = [] var defaultDatas1 = [] var labels1 = []; $.ajax({ method: "GET", url: endpoint, success: function(data){ labels1 = data.labels1 defaultDatas = data.default1 dafaultDatas1 = data.default2 var ctx1 = document.getElementById('myChart1').getContext('2d'); var myChart1 = new Chart(ctx1, { type: 'line', data: { labels: labels1, datasets: [{ label: 'Egress', data: defaultDatas, backgroundColor: ["rgb(255, 99, 132)"] }, { label: 'Ingress', data: defaultDatas1, backgroundColor: ["rgb(177, 126, 253)"], … -
Django: DB-Query inside for a class in "models.py"
Good day, inside my "models.py" in Django I want to create a new class called "Coworker" with these attributes class Coworker(models.Model): roles = ( ('Role A', 'Role A'), ('Role B', 'Role B'), ) fullname = models.CharField(max_length=255, null=False) role = models.CharField(max_length=100, null=False, choices=roles) supervisor = models.CharField(...?) I also want to create a "supervisor", which should look into this class and show me all the "fullname" with - let's say - "Role A" as choices. So of course in the beginning this field will be emtpy. Is this possible? The function "db_column" doesn't seem to work. Or am I doing something wrong? Thank you all! -
Log response time in Django views
In my view, I am logging to a file using logger.info(message) The message is a string that must contain the HTTP status and how long it took to handle the request. i can't find request-response time in HttpResponse(). What suprises me is that django.server logs the time. How did they do that? -
Cannot import views from mysite.views in Django
mysite is the app name i created in my django project. below is the hierarchy of my app. mysite --- views.py --- tasks.py --- urls.py I have a normal function(there is no request parameter, hence no entry in urls.py as well) in views.py as shown below. def function1(param1,param2): return something I am trying to import this function1 in tasks.py by using from .views import function1 but its throwing an error saying Cannot import views from mysite.views Is there any way to get rid of this error. -
Django Admin - How to (automatically) adding data to related table that can then be used to filter results?
I have tables that share information in a single related table via foreign keys. The relationships work as expected, however, I'm trying to figure out how to automatically populate fields that are then used to filter the results. I hope the example below illustrates what I'm trying to do. In the Models: class UtilType(models.Model): name = models.CharField() description = models.CharField() # following boolean fields used to filter table is_address = models.BooleanField(default=False) is_phone = models.BooleanField(default=False) is_email = models.BooleanField(default=False) is_domain = models.BooleanField(default=False) class Address(models.Model): address_type = models.ForeignKey( UtilType, on_delete=models.SET_NULL, blank=True, null=True, related_name="addresses", limit_choices_to={'is_address': True} ) class PhoneType(models.Model): phone_type = models.ForeignKey( UtilType, on_delete=models.SET_NULL, blank=True, null=True, related_name="addresses", limit_choices_to={'is_phone': True} ) ... more models with similar schema In the Admin: class ContactPhoneNumberInline(admin.StackedInline): model = PhoneNumber min_num = 0 max_num = 5 extra = 0 exclude = ["company"] fields = ( ("phone_type", "country", "phone_number"), ) class ContactEmailAddressInline(admin.StackedInline): model = EmailAddress min_num = 0 max_num = 5 extra = 0 exclude = ["company"] fields = ( ("email_type", "email_address"), ) .... more inlines w/ similar structure @admin.register(Contact) class ContactAdmin(admin.ModelAdmin): fields = ( "company", ("name_first", "name_middle", "name_last",), ("name_salutation", "name_suffix", "title"), ) inlines = [ ContactPhoneNumberInline, ContactEmailAddressInline, ContactDomainInline, ContactAddressInline ] When editing a contact, the action is as expected. I … -
Django shopping cart and order history
My project is an eCommerce project. I face the problem when I wish to submit the shopping cart into a real order, I found that all the order under the same user are sharing the same order_item I am using a boolean expression to locate the shopping cart in order model and I'm not sure is that a good idea. I would also like to know how to clean the shopping cart and transfer it into an order I will be appreciated if you could tell me how to improve :) Models: class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def __str__(self): return f"{self.quantity} of {self.item.title}" def get_total_item_price(self): return self.quantity * self.item.price class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) iscart = models.BooleanField(default=True) def __str__(self): return self.user.username def get_total(self): total = 0 for order_item in self.items.all(): total += order_item.get_total_item_price() return total Views: @login_required def add_to_cart(request, slug): item = get_object_or_404(Product, slug=slug) order_item, created = OrderItem.objects.get_or_create( item=item, user=request.user, ordered=False ) order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] # check if the order item is in the order if order.items.filter(item__slug=item.slug).exists(): order_item.quantity += 1 … -
Template only contains the last element of an array passed by context
I'm on Django 2.2 and I'm try to parse through an array in my HTML template. But for some reason, only the last element of the array is displayed. Here's mydata, we can that status is an array of str: QueryDict: {'managername': ['blabla'], 'plant': ['FR'], 'status': ['a', 'b', 'c']} This is stored in a variable that I pass through the context: context = { 'data': mydata } return HttpResponse(template.render(context, whatever)) In the HTML template, I do this : <label> {{ data.status }} </label> When I get to the HTML, here's what displayed c Is there some trick I'm missing to have the whole array and not just the last element ? -
unsupported operand type(s) for -: 'datetime.time' and 'datetime.time' when ever I calculate for OT hours and total hours
I'm trying to compute and calculate total_hours into my model. I create a method to calculate it however I'm getting an error when I do it. The error is called: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time' I just need some assistance on what to do on this one. Thanks in advance. Here is the code in question: def convert_timedelta_to_hrs(td): return decimal(td.total_seconds() / (60 * 60)) class DPRLog(models.Model): STATUS_CHOICES = ( ('PENDING', 'PENDING'), ('CANCELLED', 'CANCELLED'), ('COMPLETED', 'COMPLETED'), ) TASKS_CHOICES = ( ('TESTS EXECUTION', 'TESTS EXECUTION'), ('TESTS DESIGN', 'TESTS DESIGN'), ('MOBILE TESTING WORKSHOP', 'MOBILE TESTING WORKSHOP'), ('BENCH ACTIVITY', 'BENCH ACTIVITY'), ('DEFECT ANALYSIS','DEFECT ANALYSIS'), ) testuser = models.ForeignKey(User,on_delete = models.CASCADE,unique_for_date= 'reportDate') status = models.CharField(max_length=30, choices=STATUS_CHOICES,null=True) reportDate = models.DateField(blank=False, null=False) login = models.TimeField(blank=False, null=False) logout = models.TimeField(blank=False, null=False) total_hours = models.DecimalField(max_digits=4,decimal_places=2,null=True,blank=True) ot_hours = models.DecimalField(max_digits=4,decimal_places=2,null=True,blank=True) mainTasks = models.CharField(max_length=50, blank=False, choices=TASKS_CHOICES, null=True) remarks = models.CharField(max_length=30,null=True,blank=True,) def __str__(self): return f'{self.testuser.full_name} DPR Log' def calculate_hours(self): total_hours = self.logout - self.login - datetime.timedelta(hours=1) total_hours = convert_timedelta_to_hrs(total_hours) ot_hours=None if total_hours > 8.00: ot_hours = self.total_hours - datetime.timedelta(hours=8) ot_hours = convert_timedelta_to_hrs(ot_hours) total_hours = 8.00 return total_hours, ot_hours def save(self,*args,**kwargs): self.total_hours, self.ot_hours = self.calculate_hours() super().save(*args, **kwargs) -
Django taggit: why annotate(same_tags=Count('tags')) counts the number of common tags instead of the total number of tags?
I am following tutorials on Django 2 by Example. I don't understand step (2): Why is Count('tags') not counting the total number of tags possessed by that post? I have tried searching on Taggit's API reference but that seems not relevant. Can anyone explain it for me please? The following code: (1) searches similar posts by looking at their common tags. (2) uses Count aggregation function to generate a calculated field same_tags. (3) orders the result by the number of shared tags in descending order etc... # List of similar posts post_tags_ids = post.tags.values_list('id', flat=True) similar_posts = Post.published.filter(tags__in=post_tags_ids)\ .exclude(id=post.id) similar_posts = similar_posts.annotate(same_tags=Count('tags'))\ .order_by('-same_tags','-publish')[:4] -
Updating a user model in Django when they fill out a form on a different model
I am struggling to work out how to achieve something and would appreciate someone suggesting the correct Django way to do it. I have a custom user model which is fairly basic but includes a BooleanField which says whether they have filled out a voluntary equality and diversity form. There is a very basic model which holds the equality and diversity form data without any reference to the users which filled out each response. What I want is this, when a user fills out a valid equality and diversity form it puts True in the user model box to say they have filled out the form. I would be massively appreciative if anyone knows the correct way to do this as I am tying myself up in knots and have got myself quite confused. Here is a simplified version of the code: users/models.py class CustomUser(AbstractUser): # Has the user completed the EDI form? edi = models.BooleanField(default=False) def get_absolute_url(self): return reverse('profile', args=[str(self.username)]) equality_diversity/models.py class EqualityDiversity(models.Model): age = models.CharField(max_length=8, choices=AGE_CHOICES) ethnicity = models.CharField(max_length=64, blank=True, null=True) ... (etc) equality_diversity/views.py class EqualityDiversityView(LoginRequiredMixin, CreateView): model = EqualityDiversity template_name = 'equality_diversity.html' form_class = EqualityDiversityForm login_url = 'login' success_url = '/' def form_valid(self, form): return super().form_valid(form) -
Implement LiteSync on Django
I've tried to write sync sqlite database between 2 different Server but same app and DB. But when i turn on litesync.io in console, it doesnt synchronize the Django project with Django project in another server. I know it's wrong because i must configure it first in django project, but i've tried to change NAME of DATABASES into URI and it not work. I've tried it in console to execute query, it works, but not in Django Project. So, how to implement litesync on Django project? How to save data into Sqlite DB by URI? -
getting error : Reverse for 'detail' with arguments '(1,)' not found. 1 pattern(s) tried: [u'polls/<int:question_id>/'] in django
I am newbie here in django, when i run my app, I am getting this error Reverse for 'detail' with arguments '(1,)' not found. 1 pattern(s) tried: [u'polls/<int:question_id>/'] here i have uploaded my code for index.html and urls.py can you please check my code and help me to resolve this issue ? index.html {% if latest_question_list %} <ul> {% for question in latest_question_list %} {% if question.id %} <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li> {% else %} {% endif %} {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} urls.py from django.conf.urls import url from . import views app_name = 'polls' urlpatterns = [ url('', views.index, name='index'), # ex: /polls/5/ url('<int:question_id>/', views.detail, name='detail'), # ex: /polls/5/results/ url('<int:question_id>/results/', views.results, name='results'), # ex: /polls/5/vote/ url('<int:question_id>/vote/', views.vote, name='vote'), ] -
Can we set min max restriction on form field in views. Django
Form's Integer field quantity = forms.IntegerField() I want to set the min_value and max_value on this field in views such as form.fields['quantity'].min_value = 0 It's possible to set the initial value using form.fields['quantity'].initial = 12 But the min value is not working. Can anyone help me with that. -
Where to put customized views that inherits from django-allauth?
I have a Django project that has one app (survey), so in my project's urls.py, I have: urlpatterns = [ ... path('accounts/', include('allauth.urls')), path('survey/',include(('survey.urls','survey'), namespace='survey')), ...] I am using django-allauth to provide the authentication mechanism. However, I inherited the SignupView that is in Django-Allauth like so: class MySignupView(SignupView): def form_valid(self.request): self.user = form.save(self.request) assignmentAttendance=AssignmentAttendance.objects.create(user=user, assignment=Assignment.objects.get(id=1), status=False) assignmentAttendance.save() assignmentAttendance = AssignmentAttendance.objects.create(user=user, assignment=Assignment.objects.get(id=2), status=False) assignmentAttendance.save() try: return complete_signup( self.request, self.user, app_settings.EMAIL_VERIFICATION, self.get_success_url()) except ImmediateHttpResponse as e: return e.response The additional process (in the override the form_valid) is to create data for another model in the survey app. I do not know the best place to put the class MySignupView, so I put it in the project's urls.py and then add its view to the urlpatterns: urlpatterns = [ ... path('accounts/', include('allauth.urls')), path('survey/',include(('survey.urls','survey'), namespace='survey')), path('accounts/signup', MySignupView.as_view(), name="account_signup"), ...] Doing this works, since my MySignupView is what is called when a user wants to signup instead of the SignupView from Django-allauth. Is there a better configuration for where to writing custom views and where to put them. If so, how should it be done? I am aware that Django-allauth has a default way for adding custom form by setting the ACCOUNT_FORMS in the settings.py. …