Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
How can I fix migrations? (ValueError)
When I write py manage.py makemigrations I get ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'HiPage.user', but app 'HiPage' isn't installed. I have no AUTH_USER_MODEL in settings.py and I have no any file or app with name HiPage in my project... But I have another project with HiPage app and AUTH_USER_MODEL = 'HiPage.user' I don't know how does it influence, but it do because when I made migrations on another PC they worked... I tried to make a User model and set AUTH_USER_MODEL = 'myapp.user' but it didn't help... I tried to delete all migrations, but it didn't help... I have no more ideas -
My django application is deployed on heroku, can i use nginx to serve just the media and static files?
I deployed my django application on heroku. And, I want to know if i can serve the static and media files using nginx. I know i can use amazon s3 instead, but for now i dont have access to it yet cause i dont have a debit or credit card to complete my account. -
I want to know what does that code mean i see its not logic or inconsistent
I was trying to write simple django form and use authentication system, but some code doesn't look logic i can't relate it to the form and i don't know what is its impoertance {% extends "base.html" %} {% block content %} {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} {% if next %} {% if user.is_authenticated %} <p>Your account doesn't have access to this page. To proceed, please login with an account that has access.</p> {% else %} <p>Please login to see this page.</p> {% endif %} {% endif %} <form method="post" action="{% url 'login' %}"> {% csrf_token %} <table> <tr> <td>{{ form.username.label_tag }}</td> <td>{{ form.username }}</td> </tr> <tr> <td>{{ form.password.label_tag }}</td> <td>{{ form.password }}</td> </tr> </table> <input type="submit" value="login"> <input type="hidden" name="next" value="{{ next }}"> </form> {# Assumes you setup the password_reset view in your URLconf #} <p><a href="{% url 'password_reset' %}">Lost password?</a></p> {% endblock %} why we check if user is authenticated after checking the value of next? if someone can describe the whole process to me and , what does the code in html {% if next %} mean . -
Django template permissions not working when used inside the template of an inclusion tag
I have 2 apps in a Django Project i am using to learn django. In the app A I have an inclusion tag where I am using a template named templateA.html. This inclusion tag is being used in the app B, inside the template templateB.html. The content of templateA.html is shown properly inside templateB.html. I noticed though that when I am attempting to check permissions of the user using code similar to the following: {% if perms.my_app.can_do_something %} show something here {% endif %} then, if I include that code in templateA.html it is not working, while if I use it in templateB.html it is working properly. Is there something else that needs to be done for permissions in templates when are inside templates included in other templates? Am I missing something else here? Also in case it is relevant, to mention that i am using a custom user model based on AbstractUser so i can add some more fields to the user profile. -
heroku: "Write Access Revoked" (10k limit) and Connection Refused
I'm ok with having write access refused (I have gone over the 10k rows limit), I just need to read data in my database from my web app. The site is at africanawikic.herokuapp.com. For some reason, connections to the db are refused. Can anyone help? Thanks in advance import dj_database_url DATABASES = {'default': dj_database_url.config( default='postgres://postgres:mypassword@localhost:5432/africanawiki_geodata')} -
managing database migrations in production ? Django Migrations KeyError: ('patients', 'analysesimages')?
I have a django app deployed on AWS server and it's in the testing stage now. so I'm constantly making changes in the data model however in the last push I found that 5 migration files where lost on the server they just went missing and caused many errors as there were dependencies so on the server machine I created the missing migration files manually and the server were working fine and it worked so when i worked on other changes and tried pushing the changes I got an error that i needed to merge changes and when I did the migration files went missing on my machine and when I created them manually i get these errors on both my device and the server Blockquotefor name, instance in state.models[app_label, self.model_name_lower].fields: KeyError: ('patients', 'analysesimages') so what can i do now? and is there a better way can i manage this ? -
Using existing database with fields that contains hash and usernames (and pk)
I have an existing postgres database from online game server and would like to let people log in using there unique usernames and passwords from the game. Almost new to Django and have no clues where should I start. Where to begin? Read about custom backend authentication, but not sure how to specify that table is table of users -
Why isn't this django static files working?
I want to set the config of static files in django framework. I've tried sometimes, but It can't work correctly. In setting.py DEBUG = False STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') Some errors occurs: Uncaught SyntaxError: Unexpected token < ... I think this is static files not found error. -
hey i need a help please when i try to run the django admin server on parrot os on the terminal i get the error as
django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings