Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I'm getting "no such table: main.auth_user__old" error. How to fix this?
I have tried what's out there to fix the error provided by people here. install Django 2.7.1 delete db.sql3 makemigrations, migrate, run server. But none of this worked. Any other advice? -
Incorrect authentication data 535 python
Temos um site, e quando o usuário solicita uma nova senha, no campo esqueci minha senha, envio uma chamada para uma função em python e esta envia um e-mail para o usuário. O código é idêntico na maquina aonde foi desenvolvida a função e no servidor de hospedagem, porem no servidor de hospedagem recebo a msg: 535, b'Incorrect authentication data' É importante salientar que o servidor de hospedagem não é o mesmo servidor de e-mail, este esta hospedado em outro local funcionando perfeitamente. Não sei se isso ocorre por algum bloqueio de IP, mas não me pareceu o caso. Não sei também se é um problema com a versão do smtplib já que não consigo verificar a versão e nem realizar um update. Qualquer ajuda é bem vinda não sei mais aonde procurar e nem o que posso alterar no código para que ela funcione no servidor hospedado. Segue a função: import smtplib def enviar(email): try: fromaddr = <meu_email@meudominio.com.br> toaddr = email msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddr msg['Subject'] = "Solicitação de nova senha" body = "CORPO" msg.attach(MIMEText(body, 'html')) s = smtplib.SMTP('smtp.gmail.com', 587) s.starttls() s.login(fromaddr, "minha_senha") text = msg.as_string() s.sendmail(fromaddr, [toaddr], text) s.quit() except Exception as e: … -
Reporting script in python which create a report of database backups uploaded to S3 for each day for a fleet of 20servers
We have a fleet of 20 servers which upload backups to s3 bucket daily. We need to create and send a backup report daily in below format ServerName BackupStatus(Successful/Unsuccessful) BackupSize LastSuccessfulBackupTime How can we achieve this using a python script with boto3 -
How can I redirect users from list_view_template to detail_view_template in Django, by using slug from foreign_key and item_id together?
I am creating an image gallery in Django. Gallery consist of albums and pictures in each album. The goal is: To have albums, albums have a slug. To have a list view for each album with pictures belonging in that album. To display album name in every album. To have a detail view for each picture, the picture itself has an id, but no slug, however, the url of detail view should have album slug followed by image id. Here is what I have done so far: In Models.py: from django.db import models from django.urls import reverse class AlbumManager(models.Manager): def active(self, *args, **kwargs): return super(AlbumManager, self).filter(active=True) class Album(models.Model): name = models.CharField(max_length=200, db_index=True) active = models.BooleanField(default=True) slug = models.SlugField(max_length=200, unique=True) objects = AlbumManager() class Meta: ordering = ('name',) def __str__(self): return self.name def get_absolute_url(self): return reverse('album_details', args=[self.slug]) class Picture(models.Model): album = models.ForeignKey(Album, related_name='pictures_set', on_delete=models.CASCADE) image = models.ImageField(upload_to='pics/%Y/%m/%d', blank=True) description = models.TextField(blank=True) date = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-date',) def __str__(self): return self.album.name def get_absolute_url(self): return reverse('picture_details', kwargs={'slug': self.album.slug, 'id': self.id}) In my Views.py: from django.shortcuts import render, get_object_or_404 from .models import Album, Picture def album_details(request, album): albums = Album.objects.active() # needed for navbar dropdown menu pictures = Album.objects.get(slug=album).pictures_set.all() print('PICTURES: ', … -
'user_homeview' is not a registered namespace
**How i fix this error in django i dont know why occure thise error while i already define in url path name but occure anyone can solve this error please and tell me why occure this error which mistake due to occure error ** urls.py path("<str:username>/edit", EditProfile.as_view(), name="editprofile"), views.py class EditProfile(View): def post(self, request, *args, **kwargs): profile_obj = Profile.objects.get(user = request.user) bio = request.POST.get("Bio", "") img = request.FILES.get("image", "") if bio: profile_obj.bio = bio if img: profile_obj.userImage = img profile_obj.save() return HttpResponseRedirect(reverse("user_homeview:userpprofile", args=(request.user.username,))) -
How to get a github user API by search keyword in Python?
I am trying to use the GitHub search repository API, but I want to use optional search keywords This is my page for right now: and how can I search a user API to get that user github data? My views.py: from django.shortcuts import render from urllib.request import urlopen def index(req): return render(req, 'index.html') def user(req, username): username = str.lower(username) context = { 'username': username } return render(req, 'user.html', context) my urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.index), path('<username>', views.user), ] -
CSS file not working with django app on gpc
I am trying to run my Django app on gpc and for some reason, the CSS file is not loading for my server. I am getting the message in the image below. The CSS file seems to work properly when I run the server on my local through visual studio code so I am not sure why it's not working on gpc. What could be the reason for it not working and what can I do to fix it? Let me know if you need to see any code. -
How to use "*.objects.values()" in Django
I have a table name "Like" and column named "value". It contains two values, either "Like" or "Unlike". How do i get the column value with only "Like" using Like.objects.values(). I have tried, query = Like.objects.values({'value': 'Like'}).order_by().annotate(Count('value')) It's throwing, AttributeError: 'dict' object has no attribute 'split' The objective is to get the no of likes in descending order. If i get it using object.values(), I can do something like below to sort, sorted_dec = sorted(query, key=lambda x:x['value'], reverse=True)[0:5] Or is there any better logic to approach this? -
Cannot send email from django form
I asked a somewhat similar question but have resolved my initial issue. I would like to send an email through a form on Django using send_mail. However when I submit the form the email is not sent. This is my views.py: def assignmentSubs(request): if request.method == 'POST': assignment = AssignmentSubs(request.POST) if assignment.is_valid(): subject = 'Assignment submission: {}'.format(assignment.cleaned_data['assignment']) from_email = 'emmanuels@thegradientboost.com' message = 'Hi, Please note that {} has submitted an assignment for the {} section. We will reach out to you with more detail regarding this submission'.format(assignment.cleaned_data['link'], assignment.cleaned_data['assignment']) send_mail(subject, message, from_email, ['emmanuelsibanda21@gmail.com', 'jasmine.des8@gmail.com'], fail_silently=False,) return redirect('classroom/home.html') and my form <form method="post" action="views/students.py" class="validate"> {% csrf_token %} <div class="form-field"> <label for="assignment">Assignment Name</label> <input type="text" name="assignment" /> </div> <div class="form-field"> <label for="assignmentlink">Link to GitHub Repo</label> <input type="text" name="link" /> </div> <div class="form-field"> <label for=""></label> <input type="submit" value="Submit Assignment" /> </div> </form> -
Django HttpResponse returning weird json object
I have an ajaxrequest view that return a json object containing data from a timeseries database. When the user selects up to 15 days (in my example: from 01/01/1980 to 01/15/1980) the ajaxrequest view returns the correct object: (15) […] 0: Object { model: "vismet.stationdata", pk: 63, fields: {…} } 1: Object { model: "vismet.stationdata", pk: 64, fields: {…} } 2: Object { model: "vismet.stationdata", pk: 65, fields: {…} } 3: Object { model: "vismet.stationdata", pk: 66, fields: {…} } ... But when is selected an interval of 16 days (01/01/1980 to 01/16/1980), the view return a error where the responseText attribute would be my json object but not formatted: abort: abort(e) always: function always() catch: function catch(e) done: function add() fail: function add() getAllResponseHeaders: function getAllResponseHeaders() getResponseHeader: function getResponseHeader(e) overrideMimeType: function overrideMimeType(e) pipe: function pipe() progress: function add() promise: function promise(e) readyState: 4 responseText: "[{\"model\": \"vismet.stationdata\", \"pk\": 63, \"fields\": {\"date\": \"1980-01-01\", \"station_id\": 18, \"evapo\": 2.3524212288531, \"relHum\": 78.5, \"solarRad\": 10.7745142619028, \"maxTemp\": 27.8, \"minTemp\": 20.5, \"windSpeed\": 0.0}}, {\"model\": \"vismet.stationdata\", \"pk\": 64, \"fields\": {\"date\": \"1980-01-02\", \"station_id\": 18, \"evapo\": 2.21278972507722, \"relHum\": 82.0, \"solarRad\": 10.6113299229013, \"maxTemp\": 24.3, \"minTemp\": 17.9, \"windSpeed\": 0.0}}, {\"model\": \"vismet.stationdata\", \"pk\": 65, \"fields\": {\"date\": … -
How to create a model object with the search results data from a REST api?
I am building a search feature that allows users to search data from an external API. As of now, I transform the search results into a JSON and pass them into the template context. I have no issues displaying the search results. The results are essentially the exact information a user would use to create a new object on its own. However, I have no clue where to go in terms of allowing the user to use the specific results to construct a new object. I would like the functionality to pass the data into my CreateView and then the user would be able to create a new object with that data within the form. in views.py class GetFood(LoginRequiredMixin, TemplateView): template_name = 'search.html' def get_context_data(self, **kwargs): print(self.request.GET) # checks if there is a search_query in the request context = super().get_context_data(**kwargs) if 'search_query' in self.request.GET: query = self.request.GET['search_query'] context = search_food(query) # receives returned var 'food' from services and stores into context return context else: query = False return context in services.py def search_food(query): url = '...' r = requests.get(url, params={...}) # turns request into JSON food = r.json() return food in search.html <div class="row search_submit"> <div class="col-12"> <form method="get" action="{% … -
how to assign the foreign key for my DRF nested serializer
I'm working on an app that receives clothes "vendor, product type and sizes" from an external source that i want to save, then update the Size Charts later. but i'm not getting it to successfully save and update here's my Models.py: class Vendor(models.Model): name = models.CharField(max_length=50, null=False, blank=False) store_slug = models.CharField(max_length=100, null=False, blank=False) is_from_user = models.NullBooleanField(null=False, default=True) class Meta: ordering = ('name',) verbose_name_plural = 'Vendors' def __str__(self): return self.name class ProductType(models.Model): vendor = models.ForeignKey(Vendor,related_name='producttypes', on_delete =models.CASCADE, null=False) name = models.CharField(max_length=50, null=False, blank=False) country = models.CharField(max_length=50, default="US", null=False, blank=True) gender = models.CharField(max_length=50, default="NONE", null=False) class Meta: ordering = ('name',) verbose_name_plural = 'ProductTypes' def __str__(self): return self.name + ' | ' + self.vendor.name class Size(models.Model): producttype = models.ForeignKey(ProductType,related_name='sizes', on_delete =models.CASCADE, null=False) name = models.TextField(max_length=50, null=False, blank=False) #ready = models.NullBooleanField(default=False) class Meta: ordering = ('name',) verbose_name_plural = 'Sizes' def __str__(self): return self.name + ' | ' + self.producttype.name class Chart(models.Model): size = models.ForeignKey(Size,related_name='charts', on_delete =models.CASCADE, null=False) bust = models.DecimalField(max_digits=5, decimal_places=2, default=0.0, null=True, blank=True) hip = models.DecimalField(max_digits=5, decimal_places=2, default=0.0, null=True, blank=True) waist = models.DecimalField(max_digits=5, decimal_places=2, default=0.0, null=True, blank=True) unit = models.CharField(max_length=50, default="CM", null=False, blank=True) class Meta: ordering = ('size',) verbose_name_plural = 'Charts' def __str__(self): return self.unit + ' Chart of | '+ self.size.name + … -
How to have a manual infinite slider
I have been trying to recreate snapchat's hoop matchmaking app on django and I have realize that in the main page there is a kind of slider that shows the users "profile" and the person using it has to swipe throught this users to find a friend. The problem comes when trying to implement the slider in my project, I dont know how to have an "infinite" slider with all those profiles because I think a slider has a limited number of images(items). How can I achieve this? Any idea helps html (mates-grid-2-content which is suposed to redirect me to the previus user, mates-grid-1-content which has users info and mates-grid-3-content which is suposed to redirect me to the next user, are the main ones) <div class="mates-grid-1-1-content"> <div class="mates-grid-2-content"> prev </div> <div class="mates-grid-1-content"> <div class="mates-item-content"> <img class="mate-pic" src="{{ user.profile.profile_pic.url }}" > </div> <div class="mates-item-content"> <a href="{% url 'profile' username=content.user.username %}" style="float: left">{{ content.user }}</a> </div> <div class="mates-item-content"> <div class="responses"> <div class="response-item-img"> <img class="mates-image" src="{{ content.req_image.url }}" width="400px"> </div> <div class="response-item-bio"> <p>{{ content.req_bio }}</p> </div> <div class="response-item-button"> <button type="submit">Submit</button> </div> </div> </div> </div> <div class="mates-grid-3-content"> next </div> </div> css .mates-grid-1-1-content { display: grid; text-align: center; justify-content: center; align-self: center; grid-column: 1; grid-row: … -
With Django m2m_changed signal, is there a way to know which relation was removed?
With m2m_changed, you have both pre_remove and post_remove signals. But is there a way to determine which m2m relation is being removed in either of these hooks? I know with post_add for instance you can obtain the most recent relation as follows: from_collection = instance.name.through.objects.last().from_name to_collection = instance.name.through.objects.last().to_name Im looking for the same except for a removal. Any way this can be done? -
UNIQUE constraint failed: new__main_post.author_id in django
i added a new field to my models.py but when i try to migrate i get this error my models.py: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.OneToOneField(User, on_delete=models.CASCADE) likes = models.ManyToManyField(User, related_name='blog_posts') def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) -
Filtering posts in Django view file and viewing them via ajax
There is a problem I have been dealing with for a long time on a site I created. I can't use Ajax and Django. It is necessary to send a query to the view.py file on the main page, the posts should be sorted according to the expression of this query and should be created in a div without refreshing the page thanks to ajax. I'm not sure if I knew it. Please help someone who knows views.py: def random_ajax(request): random_query = request.GET.get('radiomarka', 'Mercedes') random_list = Person.objects.filter(country__name__icontains= random_query,is_active=True).order_by('?')[:16] return JsonResponse({'random': model_to_dict(random_list)}, status=200) urls.py: urlpatterns = [ path(r'', random_ajax , name='random_ajax'), ] Ajax: $(document).ready(function(){ $('.markselect').submit(function(e){ e.preventDefault(); var form = $(this); var serialize = form.serialize(); var action = form.attr('action'); $.ajax({ method: 'post', url: action, dataType: 'json', data: serialize, success: function(response){ $('.random_post').append('<div>Succes</div>'); }, error: function(){ window.alert('BUG'); } }); }); }); HTML: <div class="elanheader" style="font-size: 17px" > <form id="markasecimi" class="markasecimi" name="markasecimi" action="{% url 'random_ajax' %}"> {% csrf_token %} <input type="radio" name="radiomarka" value="Mercedes" id="randomMerc" {% if request.GET.get == 'Mercedes' %} checked="checked" {% endif %} onchange="autoSubmit();" hidden="hidden"> <label for="randomMerc">Mercedes</label> <input type="radio" name="radiomarka" value="Lada" id="randomLada" {% if request.GET.get == 'Lada' %} checked="checked" {% endif %} onchange="autoSubmit();" hidden="hidden"> <label for="randomLada">Lada</label> <input type="radio" name="radiomarka" value="Hyundai" id="randomHyundai" {% if request.GET.get … -
Django: ArrayField vs Multiple Rows
I'm syncing a large amount of social data for analytics and need to keep a list of user_ids and need to track what items were added or removed. These are essentially the equivalent of "friends". The maximum size of the Friends Lists will be 100-10000 entries. I have two options: Option 1 – ArrayField I can store the entire list of friend ids as an ArrayField, eg: ["298359289", "892735235", ...]. I could then do something like removed_friends = set(old_array).difference(set(new_array)) new_friends = set(new_array).difference(set(old_array)) Option 2 – Each Friend As A Row Store each friend as a separate row in the table. -- Are there any performance implications to Option 1? It seems like a vastly simpler option, but it potentially means needing to store 10,000+ items in memory. -
Django Initialize Form current user with CreateView
I wanto to display the current user in the form before submitting. views.py class PostEncabezadoReporte(LoginRequiredMixin, CreateView): login_url = '/login/' redirect_field_name = 'redirect_to' form_class = PostEncabezadoReporteForm template_name = "crear_reporte.html" def form_valid(self, form): object = form.save(commit=False) object.user = self.request.user object.startweek, object.endweek = self.weekdatetimeconverter( object.semana) object.folio = self.getfolio( object.user, object.semana, object.tipo_reporte) self.validar_unico = self.reporte_unico( object.user, object.semana, object.cliente) if self.validar_unico == 0: object.save() else: return self.form_invalid(form) return super(PostEncabezadoReporte, self).form_valid(form) forms.py class PostEncabezadoReporteForm(forms.ModelForm): class Meta: model = EncabezadoReporte fields = ('user', 'tipo_reporte', 'tipo_gasto', 'cliente', 'semana', 'folio') widgets = {'semana': forms.DateInput(attrs={'type': 'week'}), } I alreayd tried to override the init in the form and is not working, I can select the user in the field but I want it to be displayed at init. -
Daphne multi process exit working when running with supervisord. Set 4 process but only 1 keeps running
I've Daphne working with Supervisord. Config is set to have 4 simultaneous processes but it happens 3 of them exit without explanation and only one keeps running properly. I do have 2 CPUs. Supervisord config is: The output is: Then I tried changing the File descriptor: The output still show only one process Then I tried some variations: 1 - Change the file descriptor to --fd 10 2 - Replace --fd 10 with --endpoint fd:fileno=0 Same luck... or lack of luck. Am I missing something? Why I just can't have 4th processes running all time? Does it make a difference in performance between 1 and 4 for a small app? -
How can i find code snippets (related to different back-end frameworks)? [closed]
I need to find some code snippets based on codes related to frameworks like Django, Ruby, Laravel o NodeJS. Any resources or methods could help me find these snippets?? -
Django test translation hard coded
When I use translation/internationalization I use po/mo files. The problem is when I want to test translation I do it like that at the moment: from django.test import TestCase from django.utils import translation from django.utils.translation import gettext as _ # Create your tests here. class LanguageDETestCase(TestCase): def setUp(self): translation.activate('de') def test_check_languages(self): self.assertEqual(_('Home'), 'Start') self.assertEqual(_('Contact Us'), 'Kontaktiere uns') self.assertEqual(_('Sign In'), 'Anmelden') self.assertEqual(_('Sign Up'), 'Konto erstellen') self.assertEqual(_('Privacy Policy'), 'Datenschutzrichtlinie') self.assertEqual(_('Legal Disclosures'), 'Rechtliche Angaben') The problem is that I use hardcoded values. When I change the translation I also have to change the tests. Is there a way to access the key value pairs inside the po file to test. -
¿How to paginate in a detailview?
I have a question about paging, what is the correct way to paginate a content in a Detailview in django? . I have a field with a lot of data and I would like to paginate it in a detailview. I have reviewed other questions in this forum but none have worked for me I would very much appreciate your responses. Thank you -
Django Admin: Select foreign key 'children' from 'parent' change view
I have two models, parent and child (many children to one parent). I'm able to add new children to a parent in the parent change view, but I want to be able to bulk add existing parentless children to the parent, similar to the filter_horizontal option for many-to-many fields. My models look roughly like: #models.py class Parent(models.Model): name = models.CharField(max_length=50) class Child(models.Model): name = models.CharField(max_length=50) parent = models.ForeignKey(Parent,on_delete=models.SET_NULL) #admin.py class ChildInline(admin.TabularInline): model = Child @admin.register(Parent) class ParentAdmin(admin.ModelAdmin): inlines = [ChildInline,] I was thinking of using a many-to-many relationship instead and using filter_horizontal, but I want to make sure one child only has one parent and the filter_horizontal list only shows parentless children, which I'm not sure how to do. -
charts.js not loading in Django
I am using charts.js to make a chart in django. My index.html loads but the chart doesn't load. I can't figure out why its not working. I am using pipenv shell to make the virtual environment, but still no luck for some reason. I have my static folder holding my main.js, this is what's generating the graph. My urls are good because it shows my <h1> tag, but just no graph. in my terminal i do see "GET /static/main.js HTTP/1.1" 304 0 INDEX.HTML {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> <script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script> <script type="text/javascript" src="{% static 'main.js' %}"></script> </head> <body> <h1>index</h1> <canvas id="myChart"></canvas> </body> </html> MAIN.JS let labels1 = ["YES", "NO"]; let data1 = [50,50]; let colors1 = ['#49A9EA', '#36CAAB']; let myChart1 = document.getElementByID("myChart").getContext('2d'); let chart1 = new Chart(myChart1), { type; 'doughnut', data: { labels: labels1, datasets: [{ data: data1, backgroundColor: colors1 }] }, options: { title: { text: "DO YOU LIKE DOUGHNUTS?" display: true; } } }); URLS.PY from django.urls import path from . import views urlpatterns = [ path('', views.index, name="index") ] -
django : cannot read more than 100 rows by default (mysql db)
I have a Student model. And it has 101 rows in mysql database. I am trying to read all of them at once. student = Student.objects.all() for s in student: print(s) However this works only if no of rows in student table is <=100 When no of rows > 100, the query just hangs there. I do not have any pagination related settings in the project.