Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django traffic tracking
I have a website using django which has blog posts section where all blogs are summarised. you can expand the blog by going to a more detailed article on the blog by clicking "View" button which you will redirect to the necessary url. I would like to implement a feature on the detailed blog page where it shows how many visits the detailed blog has had. I am aware I can use google analytics to track this for my personal view but is they some sort of analytics sites where I can use an API to populate the data so I can show it on the page? -
How to create a demo audio file after uploading with Django?
How to create a demo audio file after uploading with Django? I am using django admin and for security reasons I need to create a demo file when an audio file is sent. This is the model class AudioFile(models.Model): name = models.CharField('Name', max_length=100) full_file = models.FileField('Fullmedia', 'upload_to='fullmedia') demo_file = models.FileField('Demo') This is the function to cut the file, note that it was using pydub to create a file with 30 seconds def make_demo(self, file): """Create a demo file with 30 secondes from real file uploaded""" song = AudioSegment.from_mp3(file) time = 30 * 1000 demo = song[:time] return demo.export(file.name + 'demo', format='mp3') What is the best way to process the upload and create this file, within the model? no admin file? -
What makes a good combinations to provide shape files on an web app?
I am attempting to develop a web app with docker. I have tried to look around and have been confused with the essential components of making one. Please bear me if you see my question is naive. This is my first attempt. I would love to use docker - to make it light weight. I have Postgres/PostGIS as data storage, and know that I can use GeoServer and other map tools, as well as GeoDjango (and other web frameworks). The question is - I am not going to provide geotiff files (no raster layers), but only shape files that people can download to make their own desk-top version maps. I am also not going to provide maps (so no need to have open layers and such). Do I need GeoServer? Would GeoDjango and PostGIS in a docker environment simply make this happen? Thank you for your help. -
Django and database connector problems
I have this installed for mysql and django , still i receive an error -Django 2.1.3 -mysql-connector-python 8.0.13 -pip 18.1 -pytz 2018.7 -setuptools 39.0.1 -virtualenv 16.0.0 -virtualenvwrapper-win 1.2.5 -wheel 0.32.3 How can i connect to mysql and django with mysql-connector. I still receive an error to install mysqlclient. Is there anything missing. please let me know -
Unexpected behavior on delete of a model row
Situation: I have two Model classes, in two different apps which are part of the same project. class doctor defined in appointments.models is a set of attributes associated with a doctor, like name, username, email, phone etc. class DoctorProfilePic is a Model defined in clinic.models, which has a StdImageField which stores images. doctor has a One to One mapping to DoctorProfilePic. class doctor(models.Model): docid = models.AutoField(primary_key=True, unique=True) # Need autoincrement, unique and primary name = models.CharField(max_length=35) username = models.CharField(max_length=15) ... profilepic = models.ForeignKey(DoctorProfilePic, blank=True, null=True, on_delete=models.CASCADE) ... class DoctorProfilePic (models.Model): id = models.AutoField(primary_key=True, unique=True) name = models.CharField(max_length=255, blank=True) pic = StdImageField(upload_to="data/media/%Y/%m/%d", blank=True, variations={ 'large': (600, 400), 'thumbnail': (150, 140, True), 'medium': (300, 200), }) doc = models.ForeignKey('appointments.doctor', blank=True, null=True, on_delete=models.CASCADE) Anticipated response: When user selects one of the profile pics from a selection box, and clicks Delete, django is supposed to delete the picture from the collection of pictures uploaded by the doctor. Problem: When the delete button is clicked, django deletes both the picture and the doctor, instead of just the former. Code: def removeprofpic(request, docid): docid = int(docid) if not IsOwnerorSuperUser(request, docid): return HttpResponse("You dont have permissions to do this.") doc = doctor.objects.get(docid = docid) if request.method == … -
python pil colour fill
I have a shape below: and I would like to colour only this shape, the background is transparent so I feel as if there is some way to colour an entire image. Right now I am using put pixel and colouring every pixel in the picture but I am wondering if there is a more efficient way to do this? putpixel(xy=(i,j), value=(red)), where i,j is coloured if it exists -
Django: limit API view output to contain only data of OAuth authenticated user?
My app requires user consent to use activity data from his Strava account (Strava is a social service for athletes). Strava uses OAuth flow for this, so the user logs in to Strava, gives his consent, and Strava redirects to a predefined URL with code added to query string that can be then exchanged for access token via another request: def strava_redirects_to_this_view(request): #strava redirects to this view after authentication, with code in query string #get tokens code = request.GET.get('code', '') # extract code from redirect URL query string access_token = exchange_code_for_token(code) # custom function to make exchange request I want my other app - running on another server - to get data of only authenticated user via API. However, I don't know how to limit the output of the API to contain only the data of the currently authenticated user. Currently my API view queries all data (activities), regardless of user: class ListActivitiesView(generics.ListAPIView): queryset = Activity.objects.all() serializer_class = ActivitySerializer I know I could limit the queryset to only logged in user if I had user registration in my app, but I would prefer not to have another registration as the user already has to log in to Strava. How would … -
Django Similar query and duplicate
Want to create user from User model. Code below class UserCreateView(CreateView): model = User fields = '__all__' template_name = 'add.html' queryset = User.objects.select_related('permission__content_type').all() But lots of duplicated query from content_type. -
How to retrieve the week value from the django model to view and pass it to the dictionary?
I just want to retrieve the week value from the model to view and pass it to the dictionary. What am I doing wrong? Model import datetime from datetime import date from django.db import models class WeekNumber(models.Model): """Week number""" objects = models.Manager() @staticmethod def number_of_week(): week = date.today().strftime("%U") return week View from django.views import View from django.shortcuts import render from .models import WeekNumber class WeekNumbers(View): model = WeekNumber template_name = 'week_number' def get(self, request): week = WeekNumber.objects.get() context = {'week': week} return render(request, 'week_number.html', context) Template <tr> <td>Week {{ week }}</td> </tr> and I have in browser: Week WeekNumber object (1) Many thanks in advance! -
Comparing two django variable in a django if block
I am having a tough time with following code. {% if object.author == user.username %} ( it is not working neither giving error) So i have articles app inside my django project. I want to make sure that if a user goes to their own post, then only they should be able to see delete and edit links(i will be placing them inside if block). Here {{object.author}} and {{user.username}} both are valid django variables. {{user.username}} specifies username of current logged in user and {{object.author}} specifies author of that particular post. Please help me out to implement with comparision logic of both variables. I am using python 3.6, django 2.1 and django template language. -
invalid literal for int() with base 10: 'Ice Cream' error
I am trying to show stock records of a particular product. While passing id of that product to stock records, it is showing invalid literal for int() with base 10: 'Ice Cream' error. My code looks like this: models.py class mProduct(models.Model): mProduct_id=models.AutoField(primary_key=True) mProduct_name=models.CharField(max_length=50) mProduct_qtyunit = models.ForeignKey(mProductUnit,on_delete=models.CASCADE) #Product ##Unit has one to many relationship with ##mProduct mProduct_qty=models.FloatField(default=0) ##current stock def __str__(self): return self.mProduct_name class mStock(models.Model): mStock_id=models.AutoField(primary_key=True) mStock_date=models.DateTimeField(default=timezone.now) mStock_product=models.ForeignKey(mProduct,on_delete=models.CASCADE) mStock_qty=models.FloatField() views.py In this view, I am trying to get object for a particular product and use it to get it's stock records through filter(). def mStockDetailView(request,id): model=mStock m=get_object_or_404(mProduct,mProduct_id=id) stock=mStock.objects.filter(mStock_product=m.mProduct_name) context={ 'stock':stock, } return render(request,'dairyapp/stock-details.html',context) template: productlist.html I passed product id as parameter with url. {% for p in product %} <a href="{% url 'dairyapp:stock-detail' id=p.mProduct_id %}"> {{p.mProduct_name}}</a> {%endfor%} urls.py path('stockrecords/<id>',views.mStockDetailView,name='stock-detail'), Despite this, I am getting invalid literal for int() with base 10: 'Ice Cream' error Can anyone provide solution for this error? Traceback: Request Method: GET Request URL: http://localhost:8000/stockrecords/5 Django Version: 2.1.3 Python Version: 3.6.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dairyapp.apps.DairyappConfig', 'widget_tweaks'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) … -
Can't access a parallel app model in Heroku
I have two projects parallel to each other: They share the same database, as indicated by the picture: I need to know if there is a way to display one model from "scalestore-app" into "scalestore-sac". -
How to filter choises in fields(forms) in Django admin?
I have model Tech, with name(Charfield) and firm(ForeignKey to model Firm), because one Tech(for example, smartphone) can have many firms(for example samsung, apple, etc.) How can I crate filter in admin panel for when I creating model, If I choose 'smartphone' in tech field, it show me in firm field only smartphone firms? Coz if I have more than one value in firm field(for example Apple, Samsung, IBM), it show me all of it. But IBM must show only if in tech field I choose 'computer'. How release it? -
Can I use and learn java and python together [on hold]
I have learned some basics of python and C++. Now I am going for Python and django in advanced ,should I learn Java with it for my future, strong basics and good Job? -
Django Show one field and associate it with another with multiple selections in the template
I need to add an amount to a service type class Factura(models.Model): cod_factura = models.IntegerField(primary_key=True) fecha = models.DateTimeField(auto_now=True) id_cliente = models.ForeignKey(Cliente,on_delete=models.CASCADE,default = none) total = models.IntegerField() class DetalleFactura(models.Model): cod_detallefactura = models.AutoField(primary_key=True) cantidad = models.IntegerField() precio = models.IntegerField() id_tiposervicio = models.ForeignKey(TipoServicio,on_delete=models.CASCADE,default = None) cod_factura = models.ForeignKey(Factura,on_delete=models.CASCADE,default = None) enter image description here class FacturaForm(forms.ModelForm): class Meta: model = Factura fields = ['cod_factura','id_cliente'] class DetalleFacturaForm(forms.ModelForm): id_tiposervicio = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple(), queryset=TipoServicio.objects.all()) class Meta: model = DetalleFactura fields = ['id_tiposervicio','cantidad'] def cfactura(request): if request.method == 'POST': form_factura = FacturaForm(request.POST) form_detalle_factura = DetalleFacturaForm(request.POST) if form_factura.is_valid() and form_detalle_factura.is_valid(): #Creacion de datos de factura factura = form_factura.save(commit=False) factura.cod_factura = form_factura.cleaned_data['cod_factura'] factura.id_cliente = form_factura.cleaned_data['id_cliente'] #Creacion detalles factura detalle_factura = form_detalle_factura.save(commit=False) detalle_factura.cantidad = form_detalle_factura.cleaned_data['cantidad'] detalle_factura.precio = detalle_factura.id_tiposervicio.valor factura.total = detalle_factura.id_tiposervicio.valor * form_detalle_factura.cleaned_data['cantidad'] detalle_factura.cod_factura = factura factura.save() detalle_factura.save() return redirect('factura:lfactura') else: form_factura = FacturaForm() form_detalle_factura = DetalleFacturaForm() return render(request,'base/cfactura.html',{'form':form_factura,'formu':form_detalle_factura}) {% csrf_token %} {{ form.as_p }} {% for tiposervicios in formu%} {{tiposervicios}} {%endfor%} <input type="submit" value="Guardar"> </form> -
Does spring framework have a module that creates database tables from Java objects?
I am new to Spring framework. I was trying to see if the framework has modules that create/update database tables from Java objects, similar to what Django python framework does. If not, is there something comparable to what Django does? -
When a django form is submitted, does the POST request contain model ID's?
I have the following django form: class AssayCompoundForm(forms.ModelForm): titrated_compound = forms.ModelChoiceField(queryset=Compound.objects.all()) fixed_compound = forms.ModelChoiceField(queryset=Compound.objects.all()) fixed_concentration = forms.FloatField() class Meta: model = AssayCompound fields = ['titrated_compound', 'fixed_compound', 'fixed_concentration'] and the following HTML: <form method="POST" enctype="multipart/form-data" id="assay-compound-form"> {% csrf_token %} <div class="row"> <div class="col-sm"> <label class="form-input">Titrated Compound</label> </div> <div class="col-sm"> {{ new_assay_compound_form.titrated_compound }} </div> <div class="col-sm"></div> </div> <div class="row"> <div class="col-sm"> <label class="form-input">Fixed Compound</label> </div> <div class="col-sm"> {{ new_assay_compound_form.fixed_compound }} </div> <div class="col-sm"></div> </div> <div class="row"> <div class="col-sm"> <label class="form-input">Fixed Concentration</label> </div> <div class="col-sm"> {{ new_assay_compound_form.fixed_concentration }} </div> <div class="col-sm"></div> </div> <input id="assay-compound-form-submit" type="submit" name="add-assay-compound" style="display:none"> The request.POST that is generated by this form looks like this: <QueryDict: {'csrfmiddlewaretoken': ['blah'], 'titrated_compound': ['3'], 'fixed_compound': ['5'], 'fixed_concentration': ['4'], 'add-assay-compound': ['Submit']}> My question is this: are the lists of strings for the user-selected 'titrated_compound' and 'fixed_compound' the model ID's assigned by Django? Or are they the indices of the indices of the ordered list generated by 'Compound.objects.all()'? -
Possible race condition between Django post_save signal and celery task
In a django 2.0 app I have a model, called Document, that uploads and saves an image to the file system. That part works. I am performing some facial recognition on the image using https://github.com/ageitgey/face_recognition in a celery (v 4.2.1) task. I pass the document_id of the image to the celery task so the face-recognition task can find the image to work on. This all works well if I call the face_recognition task manually from a DocumentAdmin action after the image is saved. I tried calling the face_recognition task from a (models.signals.post_save, sender=Document) method in my models.py, and I get an error from this line in the celery task for face_recognition: document = Document.objects.get(document_id=document_id) and the error is: [2018-11-26 16:54:28,594: ERROR/ForkPoolWorker-1] Task biometric_identification.tasks.find_faces_task[428ca39b-aefb-4174-9906-ff2146fd6f14] raised unexpected: DoesNotExist('Document matching query does not exist.',) Traceback (most recent call last): File "/home/mark/.virtualenvs/memorabilia-JSON/lib/python3.6/site-packages/celery/app/trace.py", line 382, in trace_task R = retval = fun(*args, **kwargs) File "/home/mark/.virtualenvs/memorabilia-JSON/lib/python3.6/site-packages/celery/app/trace.py", line 641, in __protected_call__ return self.run(*args, **kwargs) File "/home/mark/python-projects/memorabilia-JSON/biometric_identification/tasks.py", line 42, in find_faces_task document = Document.objects.get(document_id=document_id) File "/home/mark/.virtualenvs/memorabilia-JSON/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/mark/.virtualenvs/memorabilia-JSON/lib/python3.6/site-packages/django/db/models/query.py", line 403, in get self.model._meta.object_name memorabilia.models.DoesNotExist: Document matching query does not exist. Also, this error does not occur all the time, only … -
Are Django cron jobs processes or threads?
We are using django-cron version 0.5.1. Are these cron jobs run as separate process or are these executed as threads inside the main django process ? -
Django Create extraclass for special people
I am creating a registration form in Django. You can select between Student, Teacher, Parent or Guest. I want to create extra fields for every class. Whats the best way to do this? At the moment there will be created (example) a Student with a UserProfile (ForeignKey) my models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name="Benutzer") typeOfPerson = models.CharField(max_length=1, default=None, verbose_name="Typ", help_text="Entweder Schüler (S), Elternteil (E), Lehrer (L) oder Gast (G)") birth_date = models.DateField(default=None, verbose_name="Geburtsdatum") gender = models.CharField(max_length=1, default="M", verbose_name="Geschlecht") registration_date = models.DateField(auto_now=True, verbose_name="Registrationsdatum") ip_address = models.CharField(max_length=31, blank=True, null=True, verbose_name="IP-Adresse") is_verified = models.BooleanField(default=False, verbose_name="Ist verifiziert?", help_text="Ist der Benutzer verifiziert? (Wird z.B.: Bei manchen Umfragen gefragt.)") can_verify = models.BooleanField(default=False, verbose_name="Kann verifizieren?", help_text="Kann der Benutzer sich verifizieren? (Wenn ja, dann kann der Benutzer unter URL_ÜBER_STATIS_EINFÜGEN verifizieren.)") private = models.BooleanField(default=False, verbose_name="Privat", help_text="Ist dieses Benutzerprofil privat?") news = models.CharField(max_length=2047, blank=True, null=True) class Meta: ordering = ["user"] verbose_name = "Benutzerprofil" verbose_name_plural = "Benutzerprofile" def __str__(self): return "%s %s" % (self.user.first_name, self.user.last_name) class Student(models.Model): UserProfile = models.ForeignKey(UserProfile, on_delete=models.CASCADE) classNumber = models.CharField(max_length=2, blank=True, null=True, verbose_name="Klassenstufe") parents = models.CharField(max_length=63, blank=True, null=True, verbose_name="Eltern") def __str__(self): return str(self.UserProfile) class Parent(models.Model): UserProfile = models.ForeignKey(UserProfile, on_delete=models.CASCADE) children = models.CharField(max_length=511, blank=True, null=True, verbose_name="Kinder") def __str__(self): return str(self.UserProfile) class Teacher(models.Model): UserProfile = models.ForeignKey(UserProfile, on_delete=models.CASCADE) … -
How to host Angular 6 application in Python Django?
I am wanting to host an Angular 6 application in Django, how do I do this? -
Error while uploading with django-audiofield
Hey i am trying to use django-field but came across this error: Traceback (most recent call last): File "C:\Users\Sebastian\Envs\blog\lib\site-packages\django\core\handlers\exception.py", line 35, in inner response = get_response(request) File "C:\Users\Sebastian\Envs\blog\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Sebastian\Envs\blog\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Sebastian\Envs\blog\lib\site-packages\django\contrib\admin\options.py", line 575, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Users\Sebastian\Envs\blog\lib\site-packages\django\utils\decorators.py", line 142, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\Sebastian\Envs\blog\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Users\Sebastian\Envs\blog\lib\site-packages\django\contrib\admin\sites.py", line 223, in inner return view(request, *args, **kwargs) File "C:\Users\Sebastian\Envs\blog\lib\site-packages\django\contrib\admin\options.py", line 1557, in change_view return self.changeform_view(request, object_id, form_url, extra_context) File "C:\Users\Sebastian\Envs\blog\lib\site-packages\django\utils\decorators.py", line 62, in _wrapper return bound_func(*args, **kwargs) File "C:\Users\Sebastian\Envs\blog\lib\site-packages\django\utils\decorators.py", line 142, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\Sebastian\Envs\blog\lib\site-packages\django\utils\decorators.py", line 58, in bound_func return func.__get__(self, type(self))(*args2, **kwargs2) File "C:\Users\Sebastian\Envs\blog\lib\site-packages\django\contrib\admin\options.py", line 1451, in changeform_view return self._changeform_view(request, object_id, form_url, extra_context) File "C:\Users\Sebastian\Envs\blog\lib\site-packages\django\contrib\admin\options.py", line 1491, in _changeform_view self.save_model(request, new_object, form, not add) File "C:\Users\Sebastian\Envs\blog\lib\site-packages\django\contrib\admin\options.py", line 1027, in save_model obj.save() File "C:\Users\Sebastian\Envs\blog\lib\site-packages\django\db\models\base.py", line 729, in save force_update=force_update, update_fields=update_fields) File "C:\Users\Sebastian\Envs\blog\lib\site-packages\django\db\models\base.py", line 769, in save_base update_fields=update_fields, raw=raw, using=using, File "C:\Users\Sebastian\Envs\blog\lib\site-packages\django\dispatch\dispatcher.py", line 178, in send for receiver in self._live_receivers(sender) File "C:\Users\Sebastian\Envs\blog\lib\site-packages\django\dispatch\dispatcher.py", line 178, in <listcomp> for receiver in self._live_receivers(sender) File "C:\Users\Sebastian\Envs\blog\lib\site-packages\audiofield\fields.py", line 223, in … -
Linking charts with a DatePicker Bokeh and Django
I'm using Bokeh on top of Django and I'm having trouble allowing a widget to filter the dataframe. With the date picker, I would like that to filter what is shown in the plots, so in this case p1 and p2. Currently this only displays the plots and the datepicker but selecting a date doesn't do anything. Although in this example, filering the data and limiting the view would be equivalent, I would like to accomadate a user filtering the data and then recalculating any aggregate in the Django view. How do I make this work? def bokeh_views(request): start_date = datetime.date(2016, 01, 01) end_date = datetime.date(2018, 01, 01) df = pd.DataFrame(data={ 'reportDate': ['2016-01-01','2016-02-02','2016-03-03','2016-04-04'], 'id' : ['123','234','345','456'], }) source = ColumnDataSource(data=dict(date=df['reportDate'], close=df['id'])) day_or = ColumnDataSource(data=dict(date=df['reportDate'], close=df['id'])) hover = HoverTool( tooltips = [ ("Day", "@date{%Y-%m-%d %H:%M:%S}"), ("Value", "@close"), ], formatters={ 'date': 'datetime', 'close' : 'printf', }, ) p1 = figure(plot_height=300, plot_width=800, tools="pan, reset, box_zoom", toolbar_location='right', x_axis_type="datetime", x_axis_location="above", background_fill_color="#efefef", x_range=(dates[0], dates[30])) p1.line('date', 'close', source=source) p1.circle('date','close', source=source, size=7) p1.yaxis.axis_label = 'Reports' p1.add_tools(hover, LassoSelectTool()) p2 = figure(title="Drag the middle and edges of the selection box to change the range above", plot_height=130, plot_width=800, y_range=p1.y_range, x_axis_type="datetime", y_axis_type=None, tools="", toolbar_location=None, background_fill_color="#efefef") range_rool = RangeTool(x_range=p1.x_range) range_rool.overlay.fill_color = "navy" range_rool.overlay.fill_alpha … -
django-admin pointing outside virtualenv
I've initialised a virtual environment using the virtualenvwrapper command mkvirtualenv -a <path to project> django_project. I then installed django with pip install django. But then if i try to use django-admin i get: Traceback (most recent call last): File "/usr/local/bin/django-admin", line 7, in <module> from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' Now pip list gives me Package Version ---------- ------- Django 2.1.3 pip 18.1 pytz 2018.7 setuptools 40.6.2 wheel 0.32.3 python -m django --version gives 2.1.3 If I run which python it correctly points to my virtualenv, however which django gives: /usr/local/bin/django-admin I'd think that it should point to my venv. Why would it point to a global django admin? How do I fix it so that it'll work for my future virtual environments? I'm on MacOS using zsh and python 3.7.0. Thank you! -
Catch django signal sent from celery task
Catch django signal sent from celery task. Is it possible? As far as I know they are running in different processes @celery.task def my_task(): ... custom_signal.send() @receiver(custom_signal) def my_signal_handler(): ...