Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I fix a ProgrammingError at /admin/login/ (1146, "Table 'torquedb.showroom_customuser' doesn't exist")
I created a CustomUser using the Django allAuth package. Allowing users to sign-up and log in via email rather than usernames was the primary reason why. When I try logging into the admin with my superuser account, it throws this error: ProgrammingError at /admin/login/ (1146, "Table 'torquedb.showroom_customuser' doesn't exist") **Admin.py for the customuser ** @admin.register(CustomUser) class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser list_display = ['email', 'username', 'phone_number', 'website'] ** The CustomUser models.py ** from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): phone_number = models.IntegerField(default='07') website = models.CharField(max_length=50) def __str__(self): return f'{self.name}' I've tried running new migrations with py manage.py makemigrations py manage.py migrate py manage.py migrate showroom (the app name) I've already dropped and recreated the MariaDB database (called torquedb) a few times, and this is a new one with all migrations up to date. Again, they all state that they are up to date. -
Django not recognizing user form email verification link:
Sorry I've asked this so many times, but I've spent the last week on this like 20 hours and cannot figure it out. Yes, I'm a Django newbie. This is my very first application. I have tested the 'urlsafe_base64_encode(force_bytes(user.pk))' in shell and it works to pass the user's 'uid', however it does not work in the application itself. I get that the 'activation link is invalid' for all links even though the link passed the correct primary key, I'm not sure what is going wrong. Please help. views.py/registration page from_email, subject = 'domain <info@domain>', 'Email verification' htmly = get_template('activation_email_template.html') username = user.username message = render_to_string('activation_email.html', { 'user':user, 'token':account_activation_token.make_token(user), 'uid':urlsafe_base64_encode(force_bytes(user.pk)), }) d = {'username': username, 'url':reverse('activate', kwargs={ 'token':account_activation_token.make_token(user), 'uidb64':urlsafe_base64_encode(force_bytes(user.uid)) })} html_content = htmly.render(d) msg = EmailMultiAlternatives(subject, message, from_email,[user.email]) msg.attach_alternative(html_content, "text/html") msg.send() here is my activate/views.py: try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): ... else: return HttpResponse('Activation link is invalid!') For some reason I'm getting user is none. here is my activation_email.html: {% autoescape off %} Hi {{ user.username }}, Thanks for creating an account. Please click on the link to confirm your registration, http://domain{% url 'activate' … -
Sentry.io ignore logger dynamically
I am hoping to dynamically add loggers to a file whenever I decide to ignore a certain logger from sending to sentry, I've read the docs and this answer How to ignore a logger in the Sentry Python SDK and I believe I got it working when I has put the literal string into the ignore_logger function. When I try the below code, it doesn't ignore the logger, is there a better way to achieve this? with suppress(FileNotFoundError): with open(os.path.join(SITE_ROOT, '..', 'sentry_ignore_logger.txt')) as f: for log_line in f: ignore_logger(log_line) I had a print statement inside the loop to check it was reading the file and it printed as desired, so the issue isn't an incorrect file. The contents of the file are: django.security.DisallowedHost I'm using Djano and I've put this in my settings.py after the sentry_sdk.init (I had it before it, however that also didn't work) Thanks -
How to Run Sympy_gama in windows 10 on localhost
I am new to python and django. I want to run sympy_gama on my localhost server. i follow the documentation given by sympy_gama [ https://github.com/sympy/sympy_gamma]. but in some steps the error can be occurs. after a python deploy.py --generate-only --generate-test 1000 the ../google_appengine/dev_appserver.py . not working this command. Error is : ../google_appengine/dev_appserver.py '..' is not recognized as an internal or external command, operable program or batch file. anyone can help me? -
Is there another way to generate api key in django?
I'm building a testing application in Django that generates api key using the module Django RestFramework API Key. (Refer here: https://florimondmanca.github.io/djangorestframework-api-key/) I want to include some symbols or hyphen in the middle of the generated key. I have tried the default key generator in the module but I want to make it more secure. #models.py from rest_framework_api_key.models import BaseAPIKeyManager from rest_framework_api_key.crypto import KeyGenerator from rest_framework_api_key.models import AbstractAPIKey class UserCompanyAPIKeyManager(BaseAPIKeyManager): key_generator = KeyGenerator(prefix_length=32, secret_key_length=32) class UserCompanyAPIKey(AbstractAPIKey): objects = UserCompanyAPIKeyManager() Output: Prefix = jlxGg6bnRdjtrW3Xr6Q6yUMKWAuc0D2u -
How can I access Outlook contacts using Graph and Python?
I'm trying to access personal contacts using the graph API and Python. I can get this working for calendars and events but cannot find a way to get it working with contacts. The website doesn't provide any Python solutions to this apart from some massively out of date Django tutorials. I've read the documentation on the graph site and have attempted to edit the calendar events tutorial to fit my need but I can't get it to do what I want. Here's what I've got: My code to get the contacts: def get_contacts_personal(token): graph_client = OAuth2Session(token=token) contacts = graph_client.get('{0}/me/contacts'.format(graph_url)) return contacts.json() And my Django view code: def contacts(request): context = initialize_context(request) token = get_token(request) contacts = get_contacts_personal(token) if contacts: context['contacts'] = contacts['value'] return render(request, 'tutorial/contacts.html', context) I was hoping to get the json data but instead I get a keyword error for value. If I remove this I just get no data. I'm sure I'm missing something obvious, hopefully someone can help! -
Run DAG inside airflow container works fine but gets the AirflowException("Bash command failed") when triggered from Web
If I run the DAG inside the docker container with airflow run dag_A task_1 ... command, it works fine. But if I trigger the same DAG via the web-UI, it will fail with the following error: AirflowException: Bash command failed. Sifting through the error logs, revealed this error ImportError: No module named some-lib where some-lib is a local module inside the dag folder. I think the error is related to this question posted in SO - Apache Airflow DAG cannot import local module -
python django use mysql cursor
Cursor declared inside mysql (E.g. DECLARE cur1 CURSOR FOR SELECT id, name FROM mytable) Get returned as a variable in Python Django (e.g. a variable named abc) abc.fetch () Is it possible to use it this way? For now, receiving and printing abc only prints the contents of line x of mytable. fetch () throws an error that it is not defined. -
<option {% if 'condition.' == 'condition....'%}selected{%endif%}> </option> not working in Django custom select
I am passing two objects 'editsub_obj' and 'cat' both key-value pairs to the template. The main aim is to keep option tag selected when name from both object list matches but the code is not working. <select class="form-control" id="" name="cat_name" required> {% if not editsub_obj %} {% for data in cat %} <option value="{{data.id}}">{{data.category_name}}</option> {% endfor %} {% else %} {% for data in cat %} {% if editsub_obj.category_name == data.category_name %} <option value="{{data.id}}" selected>{{data.category_name}}</option> {% else %} <option value="{{data.id}}">{{data.category_name}}</option> {% endif %} {% endfor %} {% endif %} </select> Expected : selected should be selected with the category_name matches in both objects list. Actual : none of the options are showing as selected. -
Subtract dates in django
I'm trying to subtract two dates. I read that it could be done as simples as subtracting two class attributes but I get this error when I execute manage.py runserver expected string or bytes-like object code: class example(models.Model): date1 = models.DateField() date2 = models.DateField() diff = models.IntegerField(null=True, blank=True) def save(self, *args, **kwargs): self.diff = date1 - date2 super(example, self).save(*args, **kwargs) When I put my mouse cursor over the - symbol, PyCharm shows: "Class 'DateField' does not define 'sub', so the '-' operator cannot be used on its intances" What can I do to solve this problem/fix the operation? -
Access a methods variable
I want to access the gallery_path variable from my create_directory method as a parameter in my gallery model field. Is this possible? class Category(models.Model): category_title = models.CharField(max_length=200) category_image = models.ImageField(upload_to="category") category_description = models.TextField() slug = models.SlugField(max_length=200, unique=True, default=1) gallery = models.ImageField(upload_to=gallery_path) def create_directory(self): global gallery_path gallery_path = os.path.abspath( os.path.join(settings.MEDIA_ROOT, self.slug)) if not os.path.isdir(gallery_path): os.mkdir(gallery_path) def save(self, *args, **kwargs): if not self.pk: self.create_directory() super().save(*args, **kwargs) def delete(self, *args, **kwargs): shutil.rmtree(os.path.join(settings.MEDIA_ROOT, self.slug)) # os.rmdir(os.path.join(settings.MEDIA_ROOT, self.slug)) super().delete(*args, **kwargs) class Meta: verbose_name_plural = "Categories" def __str__(self): return self.category_title -
Django changing and saving objects of a QuerySet
I am trying to change a field in one element of the QuerySet and save it, but it doesn't seem to save. Can you tell me what I am doing wrong ? objs = sampleModel.objects.all() # below code doesn't work objs[0].text = 'NEW TEXT' objs[0].save() # below code does work index = 0 for obj in objs: if index == 0: obj.text = 'NEW TEXT' obj.save() -
How do i correctly iterate over a JSON in DJANGO
I have the following data: {"0":[{"Y":"7","J":"1038","DOUBLIN":"13","DPD":"13","DA":"7","DPD2":"7","PATTERN":"+"}], "1":[{"Y":"15","J":"1038","DOUBLIN":"-3","DPD":"-16","DA":"-1","DPD2":"-8","PATTERN":"+"}], "2":[{"Y":"31","J":"1038","DOUBLIN":"-35","DPD":"32","DA":"-17","DPD2":"16","PATTERN":"+"}], "3":[{"Y":"63","J":"1038","DOUBLIN":"-99","DPD":"64","DA":"-49","DPD2":"32","PATTERN":"+"}], "4":[{"Y":"127","J":"1038","DOUBLIN":"-227","DPD":"128","DA":"-113","DPD2":"64","PATTERN":"+"}], "5":[{"Y":"255","J":"1038","DOUBLIN":"-483","DPD":"256","DA":"-241","DPD2":"128","PATTERN":"+"}], "6":[{"Y":"511","J":"1038","DOUBLIN":"-995","DPD":"512","DA":"-497","DPD2":"256","PATTERN":"+"}], "7":[{"Y":"1023","J":"1038","DOUBLIN":"29","DPD":"-1024","DA":"15","DPD2":"-512","PATTERN":"-"}], "8":[{"Y":"2047","J":"1038","DOUBLIN":"-2019","DPD":"-2048","DA":"-1009","DPD2":"-1024","PATTERN":"-"}]} i use this code in my html which i get from ip = response.json() in views.py : {% extends 'base.html' %} {% block content %} <h2>HERE SERIOUSLY</h2> {% for i in ip %} <p>Your data is <strong>{{ i }}</strong></p> {% endfor %} {% endblock %} But the output is the first numbers only, i need to access all the data. when i try i.Y, it's blank and i expect the first one to be 7. Here's the output: Your Data is 0 Your Data is 1 Your Data is 2 Your Data is 3 Your Data is 4 Your Data is 5 Your Data is 6 Your Data is 7 Your Data is 8 Can anyone help me figure out how to correctly iterate over my json so i can build a table from all the data inside each item? Thanks -
Manage sqlite database with git
I have this small project that specifies sqlite as the database choice. For this particular project, the framework is Django, and the server is hosted by Heroku. In order for the database to work, it must be set up with migration commands and credentials whenever the project is deployed to continuous integration tools or development site. The question is, that many of these environments do not actually use the my_project.sqlite3 file that comes with the source repository, which we version control with git. How do I incorporate changes to the deployed database? Is a script that set up the database suitable for this scenario? Meanwhile, it is worth notice that there are security credentials that should not appear in a script in unencrypted ways, which makes the situation tricky. -
Django Decorator Order signals
I was reading a tutorial for signaling in django and I came across an example @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() How do we chose the order or operations? How do we know create_user_profile execs before save_user_profile? If order is decided by declaration , isn't it a bit dangerous when code is merged automatically via git or svn or whatever. -
No module named 'geopandas' Django with Apache
Everything works in python3 manage.py runserver but not working using Apache wsgi I'm using Django and Python 3.6. When i'm running runserver works perfectly ModuleNotFoundError at / No module named 'geopandas' Request Method: GET <VirtualHost *:80> ServerName website.com Alias /static /var/www/teste/static <Directory /var/www/teste/static> Require all granted </Directory> Alias /files /var/www/teste/files <Directory /var/www/teste/files> Require all granted </Directory> <Directory /var/www/teste/app/> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess teste processes=1 threads=15 python-path=/var/www/teste python-home=/var/www/teste/venv WSGIProcessGroup teste WSGIScriptAlias / /var/www/teste/app/wsgi.py ErrorLog /var/log/apache2/error_teste.log CustomLog /var/log/apache2/access_teste.log combined </VirtualHost> -
Django saving images with orm of scrapped images [duplicate]
This question already has an answer here: Django save image from url and connect with ImageField 4 answers I am not getting how to save an image that I scrapped from an external website. for example, the user name is: Jhon Doe and his images is https://randomuser.me/api/portraits/med/men/84.jpg Now I scrapped his images and name but problem is, not getting how to save the images and name with respected models/field. like my models: class Person(models.Model): name = models.CharField(max_length=50) img = models.ImageField(upload_to='somewhere'/) Now I want to upload the image with ORM in the respected user model. I also I write a management script to populate users but is populating name only, not getting how to populate images with images. Can anyone please give me a guide how do you handle this kind of problem? -
'NoneType' object has no attribute 'strip' with DjangoAdmin and Ckeditor
Hello guys I have the following problem I am using django-admin and using ckeditor, when I make a very large post and save in django-admin it gives the following error: 'NoneType' object has no attribute 'strip' # models.py class Posts(models.Model): title = models.CharField(max_length=60, blank=False, null=False, verbose_name='Título') description = models.CharField(max_length=255, blank=False, null=False, verbose_name='Descrição') content = RichTextField(blank=False, null=False, verbose_name='Conteúdo') private = models.BooleanField(blank=False, null=False, default=True, verbose_name='Privado') tags = models.ManyToManyField(Tags, verbose_name='Tags') author = models.ForeignKey(User, default=None, on_delete=models.CASCADE, verbose_name='Autor', editable=False) image = models.ImageField(upload_to='posts_img', blank=False, null=False, default='default.png', verbose_name='Imagem') status = models.ForeignKey(Status, null=False, blank=False, default=None, on_delete=models.CASCADE, verbose_name='Situação') created_at = models.DateTimeField(auto_now_add=True, verbose_name='Data Cadastro') updated_at = models.DateTimeField(auto_now=True, verbose_name='Data Atualização') class Meta: verbose_name_plural = 'Postagens' verbose_name = 'Postagem' def __str__(self): return self.title # admin.py from django.contrib import admin # Register your models here. from post.models import Posts class PostAdmin(admin.ModelAdmin): list_display = ['title', 'description', 'private', 'author', 'created_at', 'updated_at'] # Filters search_fields = ['title', 'description', 'tags', 'author', ] # Paginate per page list_per_page = 15 # No of records per page def save_model(self, request, obj, form, change): if getattr(obj, 'author', None) is None: obj.author = request.user obj.save() admin.site.register(Posts, PostAdmin) -
How to call a Django function from Angular?
I'm new in Angular, since days i'm trying to send a email. In Django, in can do it compiling my function. Now, i want to call this function from Angular. My django function receives a mail address as a parameter (mail to which the message is gonna be send). Please, help me :( -
Does get_queryset process after get_ordering in Django ListView?
I have a list view in which I implemented a search bar feature but it seems that my ordering is now not working. How do I get around this? class MemoListView(LoginRequiredMixin, ListView): model = Memo template_name = 'memos/memos.html' context_object_name = 'memos' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['memo_list'] = Memo.objects.all() return context def get_ordering(self): ordering = self.request.GET.get('ordering', '-date_time') return ordering def get_queryset(self): query = self.request.GET.get('q') if query: memo_list = Memo.objects.filter( Q(title__icontains=query) | Q(content__icontains=query)) else: memo_list = Memo.objects.all() return memo_list One thing to note is that I am implenting a filter ordering feature as well and would like to use the get_ordering method for this. Is there a way to call the get_ordering method after the get_queryset? -
Converting Django project from Python 2 to Python 3: "django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet."
After running 2to3 and installing all packages in settings.py (and requirements.txt), this error appears upon check or runserver. (env) x:languages x$ python3 manage.py check Traceback (most recent call last): File "manage.py", line 11, in <module> execute_from_command_line(sys.argv) File "/project/src/languages/env/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/project/src/languages/env/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/project/src/languages/env/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/project/src/languages/env/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/project/src/languages/env/lib/python3.7/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/project/src/languages/env/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/project/src/languages/language/__init__.py", line 3, in <module> from django_comments.models import Comment File "/project/src/languages/env/lib/python3.7/site-packages/django_comments/models.py", line 7, in <module> from .abstracts import ( File "/project/src/languages/env/lib/python3.7/site-packages/django_comments/abstracts.py", line 4, in <module> from django.contrib.contenttypes.fields import GenericForeignKey File "/project/src/languages/env/lib/python3.7/site-packages/django/contrib/contenttypes/fields.py", line 3, in <module> from django.contrib.contenttypes.models import ContentType File "/project/src/languages/env/lib/python3.7/site-packages/django/contrib/contenttypes/models.py", line 133, in <module> class ContentType(models.Model): File "/project/src/languages/env/lib/python3.7/site-packages/django/db/models/base.py", line 103, in __new__ app_config = apps.get_containing_app_config(module) File "/project/src/languages/env/lib/python3.7/site-packages/django/apps/registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "/project/src/languages/env/lib/python3.7/site-packages/django/apps/registry.py", line 135, in check_apps_ready raise AppRegistryNotReady("Apps aren't … -
Communication from Python Desktop app (Client instances) to Django server app
We have Python Desktop app installed on client systems and a web based Django application. We would like to show an alert on Django app to logged in users when the client app on their systems has not been running for let's say over 2 hours. I feel following approach should work: Hitting an API call from desktop app to Django app Storing timestamp at which the api call is received along with the client id Iterating through the active sessions on django app and checking which of the clients had hit API call before X hours and thus showing alert to those clients on web based app. I would like to keep the solution simple thus ignoring sockets as I think they will be overkill for the situation (we are looking at a frequency of checking every hour may be and there will be times when client machine is switched off as well) Can CloudWatch be any help here? Is there a better solution? -
Hide/Show li elements for independent divs
Trying to implement a hide/show results on a search page, what I have right now works, but not in the way I want. As of now, the code is limiting all li's instead of 3 per div let searchResults = document.querySelectorAll('div.test-class-3'); searchResults.forEach(function (searchResult) { console.log('result',searchResult) $(document).ready(function(){[![enter image description here][1]][1] var list = $(".search-results li"); var numToShow = 3; var button = $("#next"); var numInList = list.length; list.hide(); if (numInList > numToShow) { button.show(); } list.slice(0, numToShow).show(); button.click(function(){ var showing = list.filter(':visible').length; list.slice(showing - 1, showing + numToShow).fadeIn(); var nowShowing = list.filter(':visible').length; if (nowShowing >= numInList) { button.hide(); } }); }); }) My console.log returns two divs, these are unique, so basically forEach(searchResult) I want to only display 3 li's, each div should have the show more button. As of now, the code is limiting all li's instead of 3 per div -
Django and login "remember me": How can I view that status for other code?
I am using Django with the Allauth login code (and still a bit wet) to perform authentication. It appears that if you check "remember me", it does the following in the allauth login form: allauth forms.py (class LoginForm) if remember: request.session.set_expiry(app_settings.SESSION_COOKIE_AGE) else: request.session.set_expiry(0) return ret I am trying to use the "remember me" for other features in my app. It appears that the only 'flag' I have to determine if a user wants to be remembered or not is the above value. In my view code, I tried to read this 'flag' with the following command: request.session.get_expiry_age() Unfortunately, it always returns 1209600. Whether the user checks the "remember me" box or not, this value is 1209600. I need to find this flag so that I can use it in several places. What system variable is set and exposed when a user checks this 'Remember me' box that I am not seeing? -
Problem sending POST request image files to Django Rest Framework from React
I am trying to send image files from React to my Django Rest Framework but Django Rest doesn't seem to be picking up my data. I am not sure if it has something to do with my content-type or it's something else. This is my function in React createPainting = (data) => { console.log(data) console.log(JSON.stringify(data)) const endpoint = "/api/paintings/photos"; //notice the endpoint is going to a relative request, (relative to where the final javascript built code will be) const csrfToken = cookie.load("csrftoken"); if (csrfToken !== undefined) { // this goes into the options argument in fetch(url, options) let lookupOptions = { method: "POST", headers: { "Content-Type": "multipart/form-data; boundary=63c5979328c44e2c869349443a94200e", "Process-Data": "false", "Accept": "multipart/form-data, application/json", "X-CSRFToken": csrfToken }, body: JSON.stringify(data), credentials: "include" }; fetch(endpoint, lookupOptions) .then(response => { return response.json(); }) this.clearForm() .catch(error => { console.log("error", error); alert("An error occured, please try again later."); }); } }; The data that comes in looks like this: {srcs: "yacht3.jpeg", title_id: "109"} When I stringify it looks like this: {"srcs":"yacht3.jpeg","title_id":"109"} This is the full error message Traceback (most recent call last): File "/home/hzren/dev/t_and_b_website/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.errors.NotNullViolation: null value in column "title_id" violates not-null constraint DETAIL: Failing row contains (99, default.jpg, …