Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Shopping cart fail to display Django 2.1
I am reading django book on how to build a shopping and for some reason the product (list and detail) pages are fine but the app crash when i try to access the page that supposed to display the cart. I am not sure what the problem is but here the error from the terminal Internal Server Error: /cart/ Traceback (most recent call last): File "/Users/macadmin/Documents/Django_fun4/myshop/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/macadmin/Documents/Django_fun4/myshop/lib/python3.7/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/macadmin/Documents/Django_fun4/myshop/lib/python3.7/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/macadmin/Documents/Django_fun4/myshop/myshop/cart/views.py", line 41, in cart_detail cart = Cart(request) TypeError: __init__() takes 1 positional argument but 2 were given [11/Aug/2019 20:48:25] "GET /cart/ HTTP/1.1" 500 63026 Internal Server Error: /cart/ Traceback (most recent call last): File "/Users/macadmin/Documents/Django_fun4/myshop/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/macadmin/Documents/Django_fun4/myshop/lib/python3.7/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/macadmin/Documents/Django_fun4/myshop/lib/python3.7/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/macadmin/Documents/Django_fun4/myshop/myshop/cart/views.py", line 41, in cart_detail cart = Cart(request) TypeError: __init__() takes 1 positional argument but 2 were given [11/Aug/2019 20:48:28] "GET /cart/ HTTP/1.1" 500 63026 Internal Server Error: /cart/add/1/ Traceback (most recent call last): File "/Users/macadmin/Documents/Django_fun4/myshop/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner … -
celery periodic_task not finding tasks
I am trying to run a task every minute but with my current implementation, beat is not picking it up. If I modify my celery to add period task, it does pick it up and send it to worker but worker can't find it so it throws KeyError. Is @period_task enough for beat to find the library or it must be defined in celery.py file? Regardless, I would appreciate help. app ==>project name app conf base.py development.py production.py staging.py celery.py urls.py members models.py views.py app2 models.py views.py background tasks.py where base.py is settings.py with shared settings. My celery.py file is simply: from __future__ import absolute_import, unicode_literals import os from celery import Celery from celery.task.schedules import crontab from decouple import Config, RepositoryEnv DOTENV_FILE = '.env' env_config = Config(RepositoryEnv(DOTENV_FILE)) # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', "app.conf.development") app = Celery('app') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() in background/tasks.py I have: @periodic_task( run_every=(crontab(minute='*/1')), name="add", ignore_result=True ) def add(): … -
the pagination doesn't work with me, how I solve this problem?
The pagination doesn't work, The numbers move but the content does not change, how I solve this problem? models.py class Board(models.Model): name = models.CharField(max_length=50, unique=True) description= models.CharField(max_length=50, unique=False) class Topic(models.Model): title = models.CharField(max_length=100) created_by = models.ForeignKey(User, related_name='topics',on_delete=models.CASCADE,default=True) board = models.ForeignKey(Board, related_name='topics',on_delete=models.CASCADE) created_dt = models.DateTimeField(default=timezone.now) views.py def boards_topic(request, id): board = get_object_or_404(Board, pk=id) paginator = Paginator(board, 3) page = request.GET.get('page') # board = paginator.get_page(page) try: page_list = paginator.page(page) except PageNotAnInteger: page_list = paginator.page(1) except EmptyPage: page_list = paginator.page(Paginator.num_pages) context = {'board':board, } return render(request, 'topics.html',context) url.py path('boards/<int:id>/', views.boards_topic, name='boards_topic'), TypeError at /boards/1/ object of type 'Board' has no len() Request Method: GET Request URL: http://127.0.0.1:8000/boards/1/?page=1 Django Version: 2.2.3 Exception Type: TypeError Exception Value: object of type 'Board' has no len() -
Unable to save stripe payments to table
I followed this stripe payments tutorial: https://testdriven.io/blog/django-stripe-tutorial/. I'm using the pop-up box. I'm not sure how I can save the information to the Payments table. This is my view code. The view works, but nothing saves to the model. I'm struggling to save data from user input to my databases. Is there a good tutorial on this? I'm new to Django. class PaymentsView(TemplateView): template_name = 'page.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['key'] = settings.STRIPE_PUBLISHABLE_KEY return context from catalog.extras import generate_order_id def charge(request): # new if request.method == 'POST': try: datetime_done = datetime.now() + timedelta(days=3) order_number = generate_order_id(18) PremiumPurchase = stripe.Charge.create( user = request.user, token = request.POST['stripeToken'], description = "Purchase of Premium", datetime_payment = datetime.datetime.now(), datetime_done = datetime_done, order_id=order_number, amount=2.99, success=True, ) PremiumPurchase.save() except: raise ValidationError("The card has been declined") return render(request, 'premium/charge.html') -
How to build a Django model where the data in one field varies based on the User
I have a Customer model in Django which is linked to a User by Foreign key, so each user (engineer) can have multiple customers: class Customer(models.Model): __tablename__ = 'Customer' engineer = models.ForeignKey(User, on_delete=models.CASCADE, related_name='engineer') # other fields I now wish to add a JSONField to Customer which will hold some data I pull from a third party API: distance = JSONField(blank=True, null=True) This is great, as I can have distance information stored on a per customer basis. However this distance information would differ for each engineer/customer combination. I'm missing how I would create another model to accommodate this in an efficient manner. I suspect inheritance could be used here, but I'm struggling to figure out how to put this together. I would like to use {{customer.distance}} in the template and have the correct distance returned for the logged in user. -
Crispy Forms PrependedText and OptionsField
I am trying to put an € symbol in front of a select field but it will not render properly. That's what I would like to do: https://getbootstrap.com/docs/4.0/components/input-group/#custom-select And this is my result: This is my code that using crispy forms # This text input works perfectly Field(PrependedText("website", """<i class="fas fa-link"></i>""", css_class="col-12", wrapper_class="col-6")), # This one does not work properly Field(PrependedText('price_level', """<i class="fas fa-euro-sign"></i>""", css_class="col-12", wrapper_class="col-6")) -
Problem with ManyToManyField in other model's forms using Bootstrap
I would like to show possible choices from ManyToManyField (which I have in Homes model) in the Owners form. I have Owners <--Many2Many--> Homes with custom class HomesOwners. In Homes it works out of the box, I don't know how to make it work in Owners. I am using Django 2.2.4 with Bootstrap 4 and Postgresql. I started my project based on django-bookshelf project (also just Django and Bootstrap4). I do not use any render. Comment in django-bookshelf project mentioned How to add bootstrap class to Django CreateView form fields in the template?, so I stick to that if it comed to forms. I'm pretty new to Python (so Django too) and web technologies in general. I googled dozen of different questions/answers but I couldn't find any nice explanation of what is what and how to use it in real life. Most of them ended up with basic usage. I did some experimentation on my own, but no success so far... Here is the code I have two models - Homes/models.py and Owners/models.py Homes/models.py: class Homes(models.Model): id = models.AutoField(primary_key=True) # other fields some_owners = models.ManyToManyField(Owners, through='HomesOwners', through_fields=('id_home', 'id_owner'), related_name='some_owners') # end of fields, some other code in the class like … -
Which database design is useful for me?
i have some entities in my website and they need: 1 - having some jsonfield (needs no-sql database like mongodb) 2 - having a relation to the other table that is for comments (it must to be stored in the separated table and not embedded document in mongodb so needs sql database,like mysql) now i don't know that which way is better? 1 - using multiple databases (mongodb,mysql) at the same time and relating documents from mongodb collection,to the mysql's table and vise a versa 2 - using just mongodb and creating two separated collections and relating them with refrenceField and dismissing all other sql based options in django as a negative point! 3 - using just mysql and creating a jsonfield in the model to store json model as a column in my table 4 - any other ways that i couldn't find Thanks -
Revisited: How to configure django (2.2.4+, no fastcgi world) with nginx for windows?
How to configure Django (2.2.4+, i.e. a version without fastcgi support) to run on nginx for windows. I understand years ago it was possible to use fastcgi. Is there another way as this is no longer an option. -
Error when using two matching foreignKeys in django
I'm trying to create an inventory management system in django for keeping track of equipment used in the live events area, and I have been hitting this error when I attempt to makemigrations. I have looked hard for typos (as all the solutions I have found have been typo related) and wasn't able to find anything. I'm assuming that this has something to do with using the same foreign key twice. from django.db import models from .tools import barutils from .tools import types as choices class venue(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100, blank=False) desc = models.CharField(max_length=512, blank=True, null=True) class location(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100, blank=False) venue = models.ForeignKey(venue, on_delete=models.CASCADE, null=True) class type(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=124, blank=False) class item(models.Model): id = models.BigIntegerField(primary_key=True) type = models.ForeignKey(type, on_delete=models.CASCADE, null=False) location = models.ForeignKey(location, on_delete=models.SET_NULL, null=True, related_name="current_location") home = models.ForeignKey(location, on_delete=models.SET_NULL, null=True, related_name="home_location") out = models.BooleanField(null=True) The code above produces this error. Traceback (most recent call last): File "F:\Documents\Home\Programming\Active\Vento\venv\lib\site-packages\django\db\models\fields\related.py", line 786, in __init__ to._meta.model_name AttributeError: 'ForeignKey' object has no attribute '_meta' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "F:\Documents\Home\Programming\Active\Vento\manage.py", line 21, in <module> main() File "F:\Documents\Home\Programming\Active\Vento\manage.py", line 17, in main execute_from_command_line(sys.argv) … -
Django post-office setup
Perhaps it is just because I've never set up an e-mail system on Django before, or maybe I'm missing it... but does anyone have any insight on how to properly configure django post-office for sending queued e-mails? I've got a mailing list of 1500 + people, and am hosting my app on heroku - using the standard email system doesn't work because I need to send customized emails to each user, and to connect to the server one by one leads to a timeout. I've installed django-post_office via pip install, installed the app in settings.py, I've even been able to get an email to send by going: mail.send(['recipient'],'sender',subject='test',message='hi there',priority='now') However, if I try to schedule for 30 seconds from now let's say: nowtime = datetime.datetime.now() sendtime = nowtime + datetime.timedelta(seconds=30) and then mail.send(['recipient'],'sender',subject='test',message='hi there',scheduled_time=sendtime) Nothing happens... time passes, and the e-mail is still listed as queued, and I don't receive any emails. I have a feeling it's because I need to ALSO have Celery / RQ / Cron set up??? But the documentation seems to suggest that it should work out of the box. What am I missing? Thanks folks -
Trying to Extend Base User Model Mid-Project and Getting Unique Constraint Error
I'm trying to mimic this project: https://ruddra.com/posts/django-custom-user-migration-mid-phase-project/ Help! The problem is that I have the default base User model and want to extend that with the Profile model. I use a Django form to create the profile, when I try to save it to the Profile - it saves to base user and then I must input it myself to the Profile model, see view. After I create one profile, I am unable run create any more, I tried to update the model and am not longer able to run python3 manage.py migrate because I get the following error: django.db.utils.IntegrityError: UNIQUE constraint failed: catalog_profile.username Here is my Profile model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) key = models.CharField(max_length=25, null=True, blank=True) first_name = models.CharField(max_length=25) last_name = models.CharField(max_length=25) address1 = models.CharField(null=True, max_length=100, blank=True) address2 = models.CharField(null=True, max_length=100, blank=True, default="") zipcode = models.CharField(max_length=10, null=True, blank=True, help_text="zipcode") state = models.CharField(null=True, max_length=2, blank=True) email = models.EmailField(max_length = 250, unique=True, verbose_name = 'email_address') username = models.CharField(max_length = 25) password = models.CharField(max_length =25, null=True) @receiver(post_save, sender=User) def create_user_profile(sender, omstamce, created, **kwargs): if created: Profile.objects.create(user=instance) def __str__(self): return f'{self.first_name} ({self.last_name}) ({self.email})' Here is my views.py. It does not work, I cannot seem to save this model to profile. … -
Is there a method to post form data from one url to another url, and then render the template based on the form data
I am trying to create a simple one item product store, in which customers would go to a product page and choose the quantity they would like to purchase in a form. After completing the form, I would then like for it to redirect to the checkout page and render the quantity they chose. Is there a simple way to do this? At the moment, I am posting the form data to the product page url and then redirecting the user to the checkout page, however I am unsure how to access that data. -
implementation of the project on the ubuntu server
I would like to implement my project created in django on a ubuntu server. I do not know how to do it, in the case of nodejs just delete the node_modules file and install the modules by typing npm install Does python (django) also provide this option? how can i do this without manually installing each module -
Django validation admin panel
problem is how to add custom validations in django admin site. my case is: if check box (day) is march 2 field must contain time first < second etc.. mon = models.BooleanField(default=False) mon_from = models.TimeField(auto_now=False, null=True,blank=True) mon_to = models.TimeField(auto_now=False, null=True,blank=True) mon_location = models.ForeignKey(location, related_name='gpn', on_delete=models.SET_NULL, blank=True, null=True, verbose_name="location") tust = models.BooleanField(default=False) tust_fromfrom = models.TimeField(auto_now=False, null=True,blank=True) tust_to = models.TimeField(auto_now=False, null=True,blank=True) tust_location = models.ForeignKey(location,related_name='gwt', on_delete=models.SET_NULL, blank=True, null=True, verbose_name="location") -
Setting up Project configuration
I imported a django project from git. Now I want Visual Studio to treat it as a Django Project instead of a regular project. I tried Tools>Options>Projects and Solutions (but I see no difference in clicking the name of the tab and the General tab(not even sure if I am supposed to)) My Project Configuration in top bar is greyed out. -
static files arent working in django, but i have the same settings as another project I have done in the past?
DEVELOPMENT SERVER - Can't get my static files to work(CSS), I am not sure what I'm doing wrong but I cant seem to get them to load at all. my HTML template {% load static %} <link type="stylesheet" href="{% static 'main.css' %}" /> Settings.py STATIC_URL = '/static/' STATICFILES_DIR = [ "C:/Users/Sam/Documents/Django/Blog/OrapiApplied/static" ] My file layout /letsdoit manage.py /app /static main.css /letsdoit settings.py -
How to check if an object is being created for the first time with a custom primary key in Django?
I have the following setup in my models: import uuid class MyModel(models.Model): ... uuid = models.UUIDField( _('uuid'), default=uuid.uuid4, unique=True, primary_key=True, ) def save(self, *args, **kwargs): if not self.pk: # Do something super(MyModel, self).save(*args, **kwargs) Because of my default being overridden in my primary key field, the # Do something part of my function does not trigger, because at this point, not self.pk returns False. How can I fix this? Thanks for any help. -
Resources for creating a social media site with Django?
I want to create a social media website but havent found many resources online that can help. Can anyone recommend some? So far i have the user model so that the website can register on the site but havent any more -
Setting up local server for django
I wanted to set up the local server for my django app, but it didn't work out at all I successfully created a project via pycharm and in cmd I opened the folder with the project, than i typed 'python manage.py runserver' and i received a message showing that it executed, however i also got some 'exception in thread django-main-thread' and many traceback errors. When i tried to open http://127.0.0.1:8000/ it didn't work. I will put the whole result below. C:\Users\1>cd desktop\programming\python\django C:\Users\1\Desktop\Programming\Python\Django>python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). August 11, 2019 - 21:25:12 Django version 2.2.4, using settings 'Django.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\1\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 926, in _bootstrap_inner self.run() File "C:\Users\1\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\1\AppData\Local\Programs\Python\Python37-32\lib\site-packages\d jango\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\1\AppData\Local\Programs\Python\Python37-32\lib\site-packages\d jango\core\management\commands\runserver.py", line 139, in inner_run ipv6=self.use_ipv6, threading=threading, server_cls=self.server_cls) File "C:\Users\1\AppData\Local\Programs\Python\Python37-32\lib\site-packages\d jango\core\servers\basehttp.py", line 203, in run httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6) File "C:\Users\1\AppData\Local\Programs\Python\Python37-32\lib\site-packages\d jango\core\servers\basehttp.py", line 67, in __init__ super().__init__(*args, **kwargs) File "C:\Users\1\AppData\Local\Programs\Python\Python37-32\lib\socketserver.py ", line 452, in __init__ self.server_bind() File "C:\Users\1\AppData\Local\Programs\Python\Python37-32\lib\wsgiref\simple_ server.py", line 50, in … -
build.js error when using VueJS with Django
I'm trying to add VueJS to my Django project using webpacks. I created the vue frontend folder in my Django directory, everything works when i run npm run dev, and i can see the default Vue template. The problem is that i keep getting in my console the error GET http://localhost:8000/frontend/dist/build.js net::ERR_ABORTED 404 (Not Found) When i run my Django project. Instead of seeing the Vue default page as well, i only see a blank page and that error in my console. Here is my webpack.config.js module.exports = { entry: './src/main.js', output: { path: path.resolve(__dirname, './dist'), publicPath: 'http://localhost:8000/frontend/dist/', filename: 'build.js' }, And here are my settings: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'main/templates')], .... STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'assets'), ) WEBPACK_LOADER = { 'DEFAULT': { 'CACHE': not DEBUG, #'BUNDLE_DIR_NAME': '/dist', 'STATS_FILE': os.path.join(BASE_DIR, 'frontend/webpack-stats.json'), 'POLL_INTERVAL': 0.1, 'TIMEOUT': None, 'IGNORE:': ['.+\.hot-update.js', '.+\.map'] } } And here is what my folder looks like myfolder > frontend > dist > build.js Can someone help me finding the issue here? -
Updating user model mid-project how should I write view to save data to profile model
I'm trying to mimic this tutorial, specifically creating a Profile for a user: https://ruddra.com/posts/django-custom-user-migration-mid-phase-project/ However, I am unable to get it to work, how do I write the view to save form inputs into the Profile model. Django version == 2.2.3. Found out cannot use get_profile(), instead trying to use the signals:@receiver(post_save, sender=User). Here is my Profile model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) key = models.CharField(max_length=25, null=True, blank=True) first_name = models.CharField(max_length=25) last_name = models.CharField(max_length=25) address1 = models.CharField(null=True, max_length=100, blank=True) address2 = models.CharField(null=True, max_length=100, blank=True, default="") zipcode = models.CharField(max_length=10, null=True, blank=True, help_text="zipcode") state = models.CharField(null=True, max_length=2, blank=True) email = models.EmailField(max_length = 250, unique=True, verbose_name = 'email_address') username = models.CharField(max_length = 25) password = models.CharField(max_length =25, null=True) @receiver(post_save, sender=User) def create_user_profile(sender, omstamce, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): if instance.Profile.save() def __str__(self): return f'{self.first_name} ({self.last_name}) ({self.email})' Here is my views.py. It does not work, I cannot seem to save this model to profile. def payments(request): if request.method == "POST": form = CustomUserCreationForm(request.POST) if form.is_valid(): profile = form.save(commit=False) # WHAT SHOULD I DO HERE TO SAVE TO PROFILE MODEL user = request.user profile.key = "".join(random.choice(string.digits) for i in range(20)) profile.save() messages.success(request, f'Your account has been created! Please … -
how to display images in pdf using xhtml2pdf in django
im working on a django project and i want to generate a pdf file where the information of the user are going to be displayed, the header and the footer must be images, im creating the pdf files using xhtml2pdf library, i've read somewhere that that library does not use "real" css rules. so the image must be in pdf format, i tried to convert it but it's still not displayed. this is my view: class attestation_travail(View): def get(self, request, *args, **kwargs): template = get_template('personnel/attestation_travail.html') context = { 'url': static('images/1.pdf') } html = template.render(context) pdf = render_to_pdf('personnel/attestation_travail.html', context) if pdf: response = HttpResponse(pdf, content_type='application/pdf') n = random.randint(100, 100000) filename = "Attestation_travail_%s.pdf" %n content = "inline; filename='%s'" %(filename) download = request.GET.get("download") if download: content = "attachment; filename='%s'" %(filename) response['Content-Disposition'] = content return response return HttpResponse("Not found") and this is my html file: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Attestation de travail</title> <style type="text/css"> body { font-weight: 200; font-size: 14px; } .header { font-size: 20px; font-weight: 100; text-align: center; color: #007cae; } .title { font-size: 22px; font-weight: 100; /* text-align: right;*/ padding: 10px 20px 0px 20px; } .title span { color: #007cae; } .details { padding: 10px 20px … -
Django Model Default Datetime with Timezone Always Midnight
Current field in my model is as follows... class Test(models.Model): assigned_date_time = models.DateTimeField( null=True, verbose_name='Assigned Date', default=timezone.now) When this object is created, the assigned_date_time is always 0 or rather "midnight" of today. I'm not quite sure what I am doing wrong. Thank you in advance. -
Error for version of mysqlclient still appears, after delete if check from base.py?
OK, I have this error, like many others before me, I tried everyhing I found at google, more than 3 hours and nothing. I also install newer version but still appers, probably should I refresh packages or ? Error: django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3. Also delete if check from base.py in: path_to_projectLib\site-packages\django\db\backends\mysql\base.py First I tried with pass .. then delete whole if check, but still appers? From where it comes ?