Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Class Based View, set request.session to some value as soon as user lands on a page
I have the following need: I have some sports-betting data on my website and I need to display it in different formats according to user's location. I am talking about odds format, something like this (it's the same value): decimal: 2.00 (for Europeans) american: +100 (for Americans) I have implemented a function that is something like this and works well: def check_ip_and_set_initial_odds_format(request): country = get_country(get_client_ip2(request))['country_name'] if country == 'United States' and 'odds_format' not in request.session: request.session['odds_format'] = 'American' return request.session So basically, the idea is that if a user visits my website for the first time, the odds_format gets set automatically and the website already provides the right odds format. My question is: Can I implement this so that no matter which page the user interacts with for the first time, the odds_format gets set to the right value? For now I have implemented it on the home page, but if someone ends up on my website on a different page, odds would not display correctly. I know I could just call the function in all my views, but I was thinking of something more clever, like editing the View base class maybe? If this is the right approach, how … -
How to get query strings through GraphQL and trigger a function to return a response with Django?
We are trying to get check-boxed items list from front-end as a request query to a GraphQL endpoint and with that request trigger one function to manipulate the selected items in Django to return a response. This is for a web application to process files when get query from front-end to a GraphQL endpoint. And upload it to a s3 bucket and return a link to file as response. Using DRF we could achieve it with request.POST and getting the items with a object filter. With GraphQL how to achieve it? Do we need to use mutation or just a query is enough to trigger a function at back-end. Receive the query request with selected items list, trigger a function to manipulate the items got through query and return a response. How can we implement this with GraphQL and Django? -
List of missing records for reverse OneOnOneField in django
I have two models with the same primary key: class OperationalDevice(models.Model): ip = models.GenericIPAddressField(unique=True) mac = models.CharField() class AllowedDevice(models.Model): ip = models.OneToOneField(OperationalDevice) type = models.CharField() owner = models.CharField() I would like to display the list of all AllowedDevices that are down - kind of like: SELECT AllowedDevice.ip from AllowedDevice LEFT OUTER JOIN OperationalDevice ON AllowedDevice.ip = OperationalDevice.ip WHERE OperationalDevice.ip is NULL I tried using AllowedDevice.objects.filter(ip__...), but it creates inner join. I also tried objects.exclude and objects.annotate, and they also create a query with inner join Maybe I should't be using OneToOneField? Making the relationship go the other way is not a solution, because I need to find both kinds of exceptions - devices that are in one table but not the other. This is related to my previous question: I have two tables with the same primary key. ip mac 11.11.11.11 48-C0-09-1F-9B-54 33.33.33.33 4E-10-A3-BC-B8-9D 44.44.44.44 CD-00-60-08-56-2A 55.55.55.55 23-CE-D3-B1-39-A6 ip type owner 22.22.22.22 laptop John Doe 33.33.33.33 server XYZ Department 44.44.44.44 VM Mary Smith 66.66.66.66 printer ZWV Department The first table is automatically refreshed every minute. I can't change the database structure or the script that populates it. Both tables have ip as PRIMARY KEY. In a view, I would like … -
INNER JOIN table on custom field
I have the following models: class Keyword(models.Model): keyword = models.CharField(max_length=100) class Product(TimeStampedModel): name = models.CharField(max_length=500, unique=True) keywords = models.ManyToManyField(Keyword, related_name='products') I want to INNER JOIN Product table on custom field like this: SELECT p.name, k.keyword FROM hotshot_keyword as k INNER JOIN hotshot_product as p on UPPER(p.name::text) LIKE '%%' || UPPER(k.keyword) || '%%' WHERE p.id = 1 But I want to do that on django orm without using raw sql. Is this possible? -
DRF: strange behaviour during serialization using "source" in field
model: class Profile(models.Model): user = models.ForeignKey(User) serializer: class ProfileSerializer(serializers.ModelSerializer): user_id = serializers.UUIDField(source="user.pk") user_email = serializers.EmailField(source="user.email", read_only=True) class Meta: model = Profile exclude = ("user", ) It works fine as expected when I hit the API with retrieve action i.e, /profiles/1/ sample response: { "user_id": "xxxx", "user_email": "human@earth.com", "occupation": "software engineer", } but when I try to create a resource with the following data, the user_id field becomes to this {user: {uuid: "requested_user_id"}} like as following: { "user": { "uuid": "requested_user_id" }, "occupation": "software engineer", } I debugged this by logging serializer.validated_data. Is this desired behavior or not from DRF standpoint of view? Is there any way to prevent this to happen? I looked at the core arguments in doc but didn't find anything helpful. Thanks. -
Error when trying to run tests for python/django written in PyCharm
I am writing tests for a django program and I keep getting this error when I run it through the command line (Windows): django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. When I try running one of the test functions through PyCharm it says: Error running 'Unittests for test_models.UserTest': Can't get importable name for PyFile:test_models.py. Is it a python file in project? I know the problem has something to do with configuration settings, but I don't understand how to set these up properly. I'm relatively new to PyCharm so any help would be much appreciated. Thank you. I tried asking this question on the PyCharm forums, and I was told to ask elsewhere, because if the problem is occurring when I run tests through the command line and my IDE, it's probably not just a problem with the IDE. -
Froala editor shows only the first form
I am having some issue with this WYSIWYG editor because I have a form inside a for statement that is a comment , but Frola is loading only for the first element / form , I can't get the reason.. -
HTML video subtitles not updating after changing vtt timestamps
I made a simple django site to watch video's with subtitles. But these subtitles don't always appear at the right time. So I made a simple python script to change every timestamp in the specific .vtt file. This does work and the file changes correctly but my webpage keeps showing the previous (wrongly timed) subtitles. After a while I found out that this problem wasn't fully my fault because when I open my webpage in an incognito window it uses the right subtiles. So my conclusion was that it had something to do with chrome (and other browsers) storing the previous subtitles. Does anyone know a way around this problem? Like is it possible to change time using html or is there a way to make my website not memorize the previous subtitles? -
Can you combine permissions?
I need to know if it is possible to combine two permissions in a django python project? My boss wants me to combine the clock_in and clock_out permissions into one called clock_in_out. I also would like to just make one permission to be able to encompass add, change, view, and delete a project instead of having separate ones to assign to admins. I've tried adding in meta data to the model classes and adding @permission_required('manager.manage_project') before the applicable defs in the views.py file. I am new at python and so let me know if this is possible. I ran python3 manage.py makemigrations and migrate and it still didn't work how it should. models.py class Entry(models.Model): #uses EntryManager for querysets objects = EntryManager() no_join = models.Manager() class Meta: db_table = 'timepiece_entry' # Using legacy table name ordering = ('-start_time',) verbose_name_plural = 'entries' permissions = ( ('can_clock_in_out', 'Can use Pendulum to clock in and out'), ) views.py @permission_required('entries.can_clock_in_out') @transaction.atomic def clock_in(request): """For clocking the user into a project.""" user = request.user # Lock the active entry for the duration of this transaction, to prevent # creating multiple active entries. active_entry = utils.get_active_entry(user, select_for_update=True) initial = dict([(k, v) for k, v in request.GET.items()]) … -
Error in Django Deployment with Apache centos 7
I deployed my application in apache but Getting 500 internal server error due to some issues need assistance to get this resolved Restarted the service didn't helped me to resolved this. virtualenvironment name=djangoprojectenv path=/opt/djangoproject/djangoprojectenv/lib/python3.6/site-packages projectname - final & Application name - "final_app" project path - /opt/djangoproject/myproject/final Error Log of Apache (throwing 500 internal server error) [:error] [pid 26320] Traceback (most recent call last): [:error] [pid 26320] File "/opt/djangoproject/myproject/final/wsgi.py", line 16, in <module> [:error] [pid 26320] [application = get_wsgi_application() [:error] [pid 26320] File "/opt/djangoproject/djangoprojectenv/lib/python3.6/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application [:error] [pid 26320] django.setup(set_prefix=False) [:error] [pid 26320] File "/opt/djangoproject/djangoprojectenv/lib/python3.6/site-packages/django/__init__.py", line 27, in setup [:error] [pid 26320] apps.populate(settings.INSTALLED_APPS) [:error] [pid 26320] File "/opt/djangoproject/djangoprojectenv/lib/python3.6/site-packages/django/apps/registry.py", line 78, in populate [:error] [pid 26320] raise RuntimeError("populate() isn't reentrant") [:error] [pid 26320] RuntimeError: populate() isn't reentrant WSGI.py file [Project name - "final"] """ WSGI config for final project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "final.settings") application = get_wsgi_application() Finally my /etc/httpd/conf.d/django.conf as Alias /static /opt/djangoproject/myproject/static <Directory /opt/djangoproject/myproject/static> Require all granted </Directory> <Directory /opt/djangoproject/myproject/final> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess final python-path=/opt/djangoproject/myproject:/opt/djangoproject/djangoprojectenv/lib/python3.6/site-packages WSGIProcessGroup final WSGIScriptAlias / /opt/djangoproject/myproject/final/wsgi.py -
Re-deploying a Django application to Google Kubernetes Engine (GKS)
I followed this tutorial: https://cloud.google.com/python/django/kubernetes-engine on how to deploy a Django application to GKE. Unfortunately, I made a mistake while deploying the application, and one of my 3 pods in the cluster failed to come up. I believe I've fixed the failure, and now want to redeploy the application. I can't figure out how to do that, or if I didn't fix the error and that's why it is still in error. I don't know how to diagnose if that's the case either... After fixing my Dockerfile, I re-built and re-pushed to the Google Container Registry. It seemed to update, but I have no idea how to track this sort of deployment. How does the traditional model of pushing a new version of an application and rolling back work in GKE? -
Can I write a loop to populate the dictionary with aggregate values for creating my table
I'm trying to call my transaction object and loop through it to create a dictionary of aggregate values from transaction object. I'm trying to populate a table with these values. Is it possible to do this and if so could I please get some advice. I want the dictionary to be populated with each distinct currency the user has transacted with, current amount of currency they own so sum(current_amount) for currency for user, purchase amount for currency for user sum(purchase_amount), sold amount per currency for usersum(sold), current value per currency for user, purchase value per currency for user, and sold value per currency for user. I have data hard-coded right now for testing purposes but I want to make a loop to populate the json with results from a querie Below table id like to populate {% for total_transaction in total_transactions %} <tr> <td>{{total_transaction.currency}}</td> <td>{{total_transaction.current_amount}}</td> <td>{{total_transaction.purchased_amount}}</td> <td>{{total_transaction.sold_amount}}</td> <td>{{total_transaction.current_value}}</td> <td>{{total_transaction.purchased_value}}</td> <td>{{total_transaction.sold_value}}</td> </tr> {% endfor %} function below portfolio(request): count = Transaction.objects.filter(owner=request.user).values('currency').distinct(), context = { 'total_transactions': [{ 'currency': 'BTC', 'current_amount': 3, 'purchased_amount': 5, 'sold_amount': 2, 'current_value': 180, 'purchased_value': 400, 'sold_value': 380}, { 'currency': 'LTC', 'current_amount': 3, 'purchased_amount': 5, 'sold_amount': 2, 'current_value': 180, 'purchased_value': 400, 'sold_value': 380}, { 'currency': 'XRP', 'current_amount': 3, 'purchased_amount': … -
Data from postgres mysteriously getting deleted
I am using cookiecutter-django(https://github.com/pydanny/cookiecutter-django) for one of my live projects. And from last few days, I am observing the database data randomly getting deleted in parts. I checked logs but I found nothing. I don't know how to approach the issue to resolve it. Will really appreciate any guidance. I am using docker setup with Traefik, Postgres, Redis and celery and django. The code is deployed on a Digital Ocean Bucket. Only I have access to the bucket (Rules out the possibility of any person doing this) -
How to access a TagField from a Django model as a column in postgres?
I don't know how to select a column (skills) from a table in postgres for a Django tagfield (list of tags). My model: class CustomUser(AbstractUser): objects = CustomUserManager() position = models.CharField(max_length =10000, null=True, default='', blank=True) bio = models.CharField(max_length =10000, null=True, default='', blank=True) skills = TaggableManager(help_text="A comma-separated list of tags.") image = models.ImageField(upload_to="profile_image", blank=True) website = models.CharField(max_length=10000, null=True, default='', blank=True) I've tried SELECT skills FROM users_customuser; and I get the error 'Skills column doesn't exist' Any help would be appreciated! -
How to send the input to the code to another computer using python
I have a video file on one computer that I want to play when the other computer finishes the processing in the program. I have a Machine learning program that processes the data in one machine and according to that data then another machine plays the video as per the input from ML Model. How can I implement that? I tried with MQTT but it didn't solve my problem. -
Django Rest_Framework strange error can't import name SkippError
I just started a project and installed django rest framework, then i have added it in settings.py 's installed apps. then i run the server, it through me this error: File "/home/pyking/.local/lib/python3.6/site-packages/django/template/backends/django.py", line 125, in get_package_libraries "trying to load '%s': %s" % (entry[1], e) django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'rest_framework.templatetags.rest_framework': cannot import name 'SkipError' When removing rest_framework from installed apps, the server works nice, but if add rest_framework in settings.py 's installed apps ,it doesn't work, and throw me above error Note: The project dont have any models, view, serializers file and anything. i new project with new apps, Can you please tell me why i facing this error? -
Django is a good option to build Accounting offline apps? [on hold]
I have an idea to build an accounting app, like Sage 50 Accounting. One of the features I want to know it if is possible to build with Django is allows the user to create and open different companies, open one company at a time, that means each company created has its own database. -
What does "IntegrityError. NOT NULL constraint failed: blog_comment.post_id " stands for?
I've added a Comment model to my application, but when the form is submitted, this error pops: NOT NULL constraint failed: blog_comment.post_id Here's models.py: class Post(models.Model): title = models.CharField(max_length=100, null=True, blank=True) caption = models.CharField(max_length=100, null=True, blank=True) image = models.ImageField(upload_to='post_pics/', null=True, blank=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') text = models.TextField(null=True) date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.text def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) This is the part for creating a comment in views.py: class AddCommentView(LoginRequiredMixin, CreateView): model = Comment fields = ['text'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) My forms.py: class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['text'] -
How can I make a crontab field on Django model
I hope you are happy. I'm confused beacause I need a field for crontab But I have no logical idea. I need to send emails with timed tasks from user I make a Model like this: class crontabMail(models.Model): to=models.CharField(max_length=60,verbose_name="To mail") mailSubject=models.CharField(max_length=60,verbose_name="Mail Subject") mailText=models.CharField(verbose_name="Mail Text") startDate=models.DateField() endDate=models.DateField() cron=models.CharField(max_length=30,verbose_name="Tekrar İçeriği") User will write mail detail on a form and select start date and end date and User select timing for this email. And I wanna send a JSON like as; message: [ { to: 'birinci kişi@hotmail.com', subject: 'subject', html: 'html', begin: 'Thu Apr 25 2019 01:08:04 GMT+0300 (GMT+03:00)', end: 'Thu Apr 25 2019 15:08:04 GMT+0300 (GMT+03:00)', repeat: '0 12 */1 * *', }, How Can I make this? If you have no solution and you have Idea please Share with us. Have a nice work. -
How to create single class object when using django-celery?
I am using celery beat schedule to automatically reset an attribute at midnight. And after that I also want to send notification to all the relevant users using firebase. So, I have written following code. def send_notification(reg_ids, data_message): push_service = FCMNotification(api_key=fcm_config['GCM_API_KEY']) push_service.multiple_devices_data_message(registration_ids=reg_ids, data_message=message) @shared_task def reset_daily_count(): try: User.objects.all().update(daily_attempts=3) except Exception as e: logger.debug(e) else: send_notification(reg_ids, data_message) But this code will create the FCMNotification object, every time I will call it. What I want is to create a single object and access it from somewhere, whenever needed, even for other celery tasks, not only periodic task but normal tasks as well. How will I do it? -
Iterate through query set and compare the query set
I want to compare elements of queryset using their fields and create a new list of Sorted Objects. exam: 1)stud = Student.objects.all() 2)stud.objects.sort() the sort function will compare each item in the queryset and sort them using the sgpa, and attendance fields class StudentManager(models.Manager): def Sort(self): class Student(models.Model): name = models.CharField() sgpa = models.IntegerField() attendance = models.FloatField() objects = StudentManager() -
Sending pdf as email attachment in Django using xhtml2pdf
I am trying to attach a pdf file to an email in Django. The pdf is rendered from an html view using xhtml2pdf. The script is called every day from Heroku using the scheduler app. This part is working fine. The problem I am having is getting the pdf to attach to the email when called from the management/commands script in Django. urls.py path('pdf_report/', PDFReport.as_view(), name="Pdf_report"), views.py class PDFReport(View): def get(self, request, airport_code=None, date_code=None, shift_code=None): dates = get_perf_dates(date_code) # Render the resulting json data params = {'p_table': p_table, "airportcode": airport_code, "perfdates": dates, "shift": shift_code } return Render.render('pdf_report.html', params) render.py class Render: @staticmethod def render(path: str, params: dict): template = get_template(path) html = template.render(params) response = BytesIO() pdf = x_pisa.pisaDocument(BytesIO(html.encode("UTF-8")), response) if not pdf.err: return HttpResponse(response.getvalue(), content_type='application/pdf') else: return HttpResponse("Error Rendering PDF", status=400) and finally the automated script portion (in management/commands) Send_PDF.py from django.core.management.base import BaseCommand from django.core.mail import EmailMessage from ...views import PDFReport from ...models import DistributionList class Command(BaseCommand): help = "Sends out an email when called" def handle(self, *args, **options): '''Contact page view for technical support requests''' mail_d_list = [] for users in DistributionList.objects.all(): #.values_list('email', flat=True) mail_d_list.append(users.email) mail_name.append(users.name) self.stdout.write(str(mail_d_list)) # For testing purposes mail_subject = "Daily Report" mail_content = … -
Is there a way to read more than one value per key (xmltodict) with jinja2?
I want to show the response of a web-service request (GET), arriving as xml, in html page with jinja2. When the key has only one value it works, with more values it doesn't. What am I missing? {% for key5, value5 in value4.items %} {% if key5 == 'sublibrary' %} {% for key6, value6 in value5.items %} Values: {{ key6 }}, {{ value6 }}<br> {% if key6 == 'open-sum' %} <h3>Sum: {{value6}}</h3> {% endif %} {% endfor %} {% endif %} {% endfor %} If key5 has only one 'open-sum' it shows the result, if it has more than one, it shows nothing. Shouldn't the "for" look in every tag? -
determine the default object type foe the user model when you have multiple types from the same model
I create 2 objectTypes from the user model: class UserType(DjangoObjectType): # ... class Meta: model = get_user_model() and class TopRankedUsersType(DjangoObjectType): posts_count = graphene.Int() replies_count = graphene.Int() class Meta: model = get_user_model() only_fields = ['id', 'username', 'photo', 'date_joined', 'points'] everything works fine, but I noticed that the default type to represent a user type is TopRankedUsersType django / graghQl API -
Django test multiple pages
The test is suppose to login with a user, favourite a video and check that it appears on a certain page. def sometest(self): self.client.login(username='testUser', password='testPassword') user = auth.get_user(self.client) assert user.is_authenticated # check user is logged it new_object_2 = SampleModel.objects.create(unique_id='123456', name='sample') self.client.get(reverse('page:favourite_post', kwargs={'fav_id': new_object_2.id}))) response_2 = self.client.get(reverse('page:bookmarked')) self.assertContains(response_2, 'sample') #test fails My url file is path('favourite_post/<int:fav_id>', views.favourite_post, name='favourite_post'), path('bookmarked_video/', views.bookmarked.as_view(), name='bookmarked'), The views.py is def favourite_post(request, fav_id): post = get_object_or_404(Post, id=fav_id) if request.method == 'POST': if post.favourite.filter(id=request.user.id).exists(): post.favourite.remove(request.user) else: post.favourite.add(request.user) return HttpResponseRedirect(reverse('page:some_page', args=(fav_id,))) How can I modify the above test to check that the post appears in the bookmarked page ?