Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 ? -
I need some help figuring out this error when trying to post a password
I'm getting an ValueError Exception Value: Invalid salt when I'm using bcrypt to post a login and password in my django app. I've tried using utf-8 to encode it but so far it doesn't seem to work. Do I need to decode it as well? Here is the code that I have: def authenticate(request): hashed_password = bcrypt.hashpw(request.POST['password'].encode('utf-8'), bcrypt.gensalt()) user = User.objects.create(first_name=request.POST['first_name'], last_name=request.POST['last_name'], password=hashed_password, email=request.POST['email']) user.save() request.session['id'] = user.id return redirect('/success') def login(request): if (User.objects.filter(email=request.POST['login_email']).exists()): user = User.objects.filter(email=request.POST['login_email'])[0] if (bcrypt.checkpw(request.POST['login_password'].encode(), user.password.encode())): request.session['id'] = user.id return redirect('/success') return redirect('/') Thanks for the help! -
How to change True value into green check in the Django admin ListView
models.py class Example(models.Model): sort = models.PositiveIntegerField(default=0, blank=False, null=False) created = models.DateTimeField(editable=False) modified = models.DateTimeField(editable=False) online = models.BooleanField(default=True) title = models.CharField(max_length=300, blank=True) slug = models.SlugField(max_length=255, blank=True, unique=True) main_image = models.ImageField(upload_to='images', blank=True) def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) if not self.id: self.created = timezone.now() self.modified = timezone.now() super().save(*args, **kwargs) def image_tag(self): if self.main_image: return True As you can see if you have BooleanField online - it will change the True or False to Green or Red. How can I achieve - that when my ImageField is empty it would do the same. I have created an image_tag method that would return True or False but not sure what to do next - do I need to override the template - is there a way to do it without? -
Replacing default forms in django-postman via urlpatterns and views
django-postman docs say that you can replace the default forms in views with this: urlpatterns = patterns('postman.views', # ... url(r'^write/(?:(?P<recipients>[^/#]+)/)?$', WriteView.as_view(form_classes=(MyCustomWriteForm, MyCustomAnonymousWriteForm)), ) But what is patterns? Where do I import that from, and where would this code go? In the project's urls.py? -
unable to get all grade(manytomanyfiled) in django detailview
i want to get subject according to grade. (E.g English include in grade 5th,6th etc)i have tried many thing but unable to get manytomany filed view in detailview i have tried queryset tag on template and queryset function in detailview model.py class grade(models.Model): Grade = models.CharField(null = True,max_length=100) slug = models.SlugField( default='',editable=False,max_length=100) def save(self, *args, **kwargs): self.slug = slugify(self.Grade) super(grade, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('grade-detail', kwargs={'pk': self.pk}) def __str__(self): return "%s " % (self.Grade) class subjects(models.Model): Book = models.CharField(null = True,max_length=100) Grade = models.ManyToManyField('grade') slug = models.SlugField( default='',editable=False,max_length=100) def save(self, *args, **kwargs): self.slug = slugify(self.Book) super(subjects, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('subjects-detail', kwargs={'pk': self.pk}) def __str__(self): return "%s " % (self.Book) view.py class subjectsdetailview(DetailView): model = subjects template_name = 'myapp/subjects_detail.html' def get_queryset(self): mysub = subjects.objects.order_by('Book') return mysub my html tag code <h3>Detail</h3> <ul><h5>Subject: <font color="blue">{{subjects.Book}}</font></h5> </ul> <ul><h5>Grade: <font color="blue">{{subjects.Grade.all}}</font></h5> </ul> <a href="{% url 'subjects-delete' subjects.id %}" class="btn btn-outline-primary" role="button" aria-pressed="true">Delete</a> <a href="{% url 'subjects-update' subjects.id %}" class="btn btn-outline-primary" role="button" aria-pressed="true">Edit</a> result isenter image description here -
psycopg2.errors.StringDataRightTruncation: value too long for type character varying(2) Django
I am deploying my Django website on Heroku and facing this error while migrating. My website is up and running on localhost but while deploying facing this error. This is my models- from django.db import models from django.contrib.auth.models import User from django.db.models.signals import pre_save from Dipesh_Pal.utils import unique_slug_generator # Create your models here. class Home(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(max_length=255, null=True, blank=True) body = models.TextField() CATEGORY_CHOICES = [ ('NEWS', 'News'), ('ANDROID', 'Android'), ('PC', 'PC'), ('OTHERS', 'Others'), ] category = models.CharField( max_length=20, choices=CATEGORY_CHOICES, default='OTHERS', ) link = models.URLField(blank=True) date = models.DateTimeField(auto_now_add=True) pub_date = models.DateTimeField(auto_now_add=True) thumb = models.ImageField(default='default.png', blank=True) author = models.ForeignKey(User, default=None, on_delete=models.CASCADE) def __str__(self): return self.title def snippet(self): return self.body[:100]+'...' def get_absolute_url(self): return '/' + self.title def slug_generator(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = unique_slug_generator(instance) pre_save.connect(slug_generator, sender=Home) I am getting this error while migrate- python manage.py migrate You may have some problem with YouTube Instagram Followers: 341 You may have some problem with Twitter Operations to perform: Apply all migrations: accounts, admin, auth, contenttypes, home, sessions, sites Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying accounts.0001_initial... OK Applying accounts.0002_auto_20190226_1249... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying … -
How to use Select2 as the POSTMAN_AUTOCOMPLETER_APP for django-postman?
Using Django-postman, can I set Django-select2 as the POSTMAN_AUTOCOMPLETER_APP? If so, how can I configure it to work? Specifically, what do I need to set these values to? ‘field’ The model class name. Defaults to ‘AutoCompleteField’ ‘arg_name’ The name of the argument Defaults to ‘channel’ ‘arg_default’ No default value. This is a mandatory default value, but you may supersede it in the field definition of a custom form or pass it in the url pattern definitions. -
How to keep message strings separate in Django app
Is there any official way to keep message strings in separate file, like Android strings.xml? In android, we can use a string in different place without duplication. If there is no way, what's the best practices?