Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
csv file not being uploaded in django admin
In my Django admin i am uploading my csv with summary and issue key id column. I am able to upload my csv but whenever in row 2 if i add (",") it shows error "Failed to parse csv". but instead if i add any other special character under summary and test case id it works. can anyone help me? Forms.py def clean_csv_file(self): value = self.cleaned_data['csv_file'] if not value.name.endswith('.csv'): raise forms.ValidationError('Invalid file type') try: data = pd.read_csv(value.file, encoding = 'ISO-8859-1', engine='python') data.columns= data.columns.str.strip().str.lower() data=data.rename(columns = {'test case id':'Test Case ID'}) def transform(df): my_new_string = re.sub('[^a-zA-Z0-9"''-_“” \n\.]', '', df) return my_new_string data['summary'] = data['summary'].apply(transform) except KeyError: raise forms.ValidationError( 'CSV file must have "summary" column and "Issue Key" column') except Exception as e: print('Error while parsing CSV file=> %s', e) raise forms.ValidationError('Failed to parse the CSV file') return data csv-1 (This doesn't work because of ") Test Case ID,summary "," TCMT-10,Verify that Process CSV sub module is displayed under “Process CSV” module on Dashboard of Client’s user. TCMT-11,Verify that only View to “Duplicate test cases” under “Test_Suite_Optimizer” module on Dashboard of Client’s user. TCMT-12,Verify that Process CSV sub module is displayed under “Process CSV” module on Dashboard of Client’s user. TCMT-13,Verify that … -
how to set min date of jquery date picker depending on the models.DateField in django
class Post(models.Model): ref_no = models.CharField(max_length=6, null=True, blank=True, unique=True) select_section = models.CharField(max_length=20, choices=Sections) incident = models.TextField(max_length=500, help_text="Mention the incident in brief here.") severity = models.CharField(max_length=20, choices=Severity) date_posted = models.DateField(auto_now_add=True, auto_now=False, blank=True) confirm_closing = models.BooleanField(default=False, help_text="Please confirm to close the Ticket") comment = models.TextField(max_length=500, default="Issue resolved and this Ticket has been closed successfully!") date_closed = models.DateField(null=True, blank=False, auto_now_add=False, auto_now=False) username = models.ForeignKey(User, on_delete=models.CASCADE) This is my model Here i want my min_date for date_closed field should be greater than the date_posted field of my model....please let me know what to do.....thanks in advance -
Nested Serializer for Django to nest subfields
I have a viewset which retrieves a queryset (Region.objects.filter(id=region_id)), and I want to serialize the queryset to include a number of tables referenced by foreign key like so: Region >> Market >> Baskets >> Fruits Each fruit has a basket_id Each basket has a market_id Each market has a region_id I have a serializer: class RegionSerializer(serializers.ModelSerializer): markets = serializers.SerializerMethodField() class Meta: model = Region fields = '__all__' def get_markets(self, obj): return ==(list(obj.region_set.all().filter(region_id=obj.id).values())) So far this works great to retrieve the market list, but I want to nest it so I have a region, a list of individual markets on the region, a list of individual baskets on each market, and a list of individual fruits on each basket. I'm not entirely sure how to accomplish said subfields using the serializer. -
Django allauth use email instead username to identify user
I want to use only an email of a user to identify him/her. Now I thought I will just define User class like so: class User(AbstractUser, CreatedUpdatedAtMixin): email = models.EmailField(_('email address'), unique=True) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) username = None USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() class Meta: verbose_name = _("User") verbose_name_plural = _("Users") But I also want to use django-allauth for sign up, login, email verification and so on. django-allauth adds EmailAddress table, which holds all emails for each user (there can be more than one email for user) and as a result I have emails duplicated (in User table and in EmailAddress table). How can I resolve this issue? I thought about deleting email from User but then user API is ugly (user.email_set.all()[0] :/). What's my best pick here? Just go along with duplication or should I implement allauth stuff myself, or hopefully there is some other option? -
Django get objects from url slug not working
I'm trying to make it so that I can show only briefs with the slug name as the category, however it does not work. At the minute I can only use it by showing all briefs using .objects.all() however this is not suitable for my desired use case. Do i need a slug field in the brief section too? Models.py class Category(models.Model): name = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=50, unique=True) class Meta: verbose_name_plural = 'categories' verbose_name = 'category' def __str__(self): return self.name def get_absolute_url(self): return reverse('browse') class Brief(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) brandname = models.CharField(max_length=28) description = models.CharField(max_length=200) date = models.DateTimeField(auto_now=True, blank=True) category = models.ForeignKey(Category, on_delete=CASCADE) def get_absolute_url(self): return reverse('homepage') Urls.py path('browse/categories/<slug:catslug>/', views.postsinthecategory, name = 'catslug' views.py def postsinthecategory(request, catslug): categories = Category.objects.all() brief = Brief.objects.all() if catslug: category = get_object_or_404(Category, slug = catslug) brief = Brief.objects.get(category=catslug) template = 'users/categoryposts.html' context = {'categories': categories, 'brief': brief, 'category': category} return render(request, template,context) -
Django filter for result from checkbox form
I'm begginer of django and i try to implement search engine to look for recipes that contains selected ingredients. I want to do form with all ingredients_type from my Model and user can select up to 3 of them (checkbox prefered). Then i want to filter recepe that contains them. I was looking for generic form but never get right result. Right now i have only a scratch and Im looking for any advice model.py class IngredientsType(models.Model): type = models.CharField(max_length=60, blank=True) def __str__(self): return self.type search.html {% for ingredients in ingredients_type %} <input type="checkbox" id="{{ingredients.type}}"> <label for="{{ingredients.type}}">{{ingredients.type}}</label> {% endfor %} <form method="POST" action="#"> <button type="submit" name="save" value="save">szukaj</button> </form> Do i have to create custom form or there is good way to use some of generic form? -
Django rest framework list of manytomany relational fields
I am trying to create an app that allows for me to upload my artwork and also have a carousel of a subset of those artworks. I want to have a Carousel object that I select images for it. from django.db import models from artwork.models import Artwork # Carousel Model references the artworks in a many to many field class Carousel(models.Model): carouseltitle = models.CharField(max_length=200,) artwork = models.ManyToManyField(Artwork) class Meta: verbose_name = 'Carousel' verbose_name_plural = 'Carousels' def __str__(self): return self.carouseltitle In my serializer, very simply creates what I want except for pulling Artwork fields: from rest_framework import serializers from .models import Carousel from artwork.models import Artwork class CarouselSerializer(serializers.ModelSerializer): id = serializers.ReadOnlyField() class Meta: model = Carousel fields = ('id', 'carouseltitle', 'artwork') My view: from django.shortcuts import render from .models import Carousel from .serializers import CarouselSerializer from rest_framework import generics # Create your views here. class CarouselListCreate(generics.ListCreateAPIView): queryset = Carousel.objects.all() serializer_class = CarouselSerializer Creates this output: [ { "id": 7, "carouseltitle": "Home", "artwork": [ 2, 4, 6 ] } ] For the artwork list, I want to list field from the artwork such as the url to the image and the title, not just the PK. For the life of me everything … -
Will I have metatags for Google index in a reactjs application with using just Helmet?
First of all, apologies for my English. I have a reactjs application that requires to be crowded by Google. This application has multiple pages, so for a better indexing I tried to use Gatsby and I put everything in a Django server. I know that the interaction between the react app and the Django app could be better, but right now another guy is developing the backend part. I'm just wondering if I could provide him a single page app with a Helmet code for each "page" instead using Gatsby. So the Django template will point directly to the built index of my entire application and the part of indexing is made from my side with Helmet -
RelatedObjectDoesNotExist at /profile/
I have am trying to send the signal do that is the user create the account it automically create the profile for the user but I think i have messed things while creating signal.py it register the user but donot create the profile for the user views.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from .forms import UpdateUserForms, ProfileUpdateForm from login.forms import UserRegisterForm from django.contrib import messages # Create your views here. @login_required def profile(request): if request.method == 'POST': u_form = UpdateUserForms(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account is updated!') return redirect('profile') else: u_form = UpdateUserForms(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form } return render(request, 'profile.html', context) def register(request): form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account Registeration Successful!!! for { username }') return redirect('home') else: form = UserRegisterForm() return render(request, 'register.html', {'form': form}) signal.py so that it sends signal to create an userprofile automatically if user is register from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile #to create new profile @receiver (post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) #to update … -
Get specific list of data after filter in django
I tried to create a list of all the articles from a subscription with a URL. My Models are, class Subscription(models.Model): name = models.CharField(max_length=30) thumbnail = models.URLField() class Article(models.Model): subscription_name = models.ForeignKey(to=Subscription, on_delete=models.CASCADE) published = models.DateTimeField() title = models.CharField(max_length=300) Home Page View with all subscriptions: class HomeListView(ListView): model = Article template_name = "home.html" ordering = ['-published'] paginate_by = 20 context_object_name = 'allData' To make it more clear. Home page is shown with all articles from all subscriptions. If I click on a subscription, I wanna display all the articles by that subscription. How to implement the query for views.py for the problem? -
Python Django Channels - Is better to isolate the WebSocket Server?
So I have a Django application with React front-end through an API (django-restframework) and I would like to implement some websocket action (real time events) with Django Channels, is it better to create another server, just to websocket connections or integrate all in one application? I know it would change to ASGI, but don't know what it can causes or malfunction with HTTP connections after that. Thanks. -
Django-messages app - display message as a conversation
I'm beginning with Django and I had a glace at Django-messages app. I decided to follow the way they do. Thanks to parent_message and timestamp we could display a view conversation (sender & receiver). In my message_view.html I got the last message (which is in reality a message from a user) and I got the possibility to answer the message thanks to reply views. Does anyone has an idea about how display the whole conversation. I got in my template the first two steps: last message (message.id, which is in reality a message from a user) form to answer () the all conversation (parent_messages of message.id in order with timestamp) message/models.py class Message(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='sender') receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name='receiver') message = models.CharField(max_length=1000) parent_message = models.ForeignKey('self', related_name='next_messages', null=True, blank=True, on_delete=models.SET_NULL) timestamp = models.DateTimeField(auto_now_add=True) read_at = models.DateTimeField(_("read at"), null=True, blank=True) replied_at = models.DateTimeField(_("replied at"), null=True, blank=True) #is_read = models.BooleanField(default=False) def new(self): if self.read_at is not None: return False return True def replied(self): if self.replied_at is not None: return True return False def __str__(self): return self.message class Meta: ordering = ('timestamp',) def inbox_count_for(user): return Message.objects.filter(receiver=user, read_at__isnull=True).count() message/views.py @login_required def view(request, message_id, form_class=ComposeForm, quote_helper=format_quote, subject_template=_(u"Re: %(subject)s"), template_name='message_view.html'): user = request.user … -
Django: ContentType matching query does not exist
I am creating a comment thread for my project and I faced above stated error. here is the traceback: Traceback (most recent call last): File "D:\GitHub\Portfolio\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\GitHub\Portfolio\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\GitHub\Portfolio\comments\views.py", line 22, in comment_thread content_type = ContentType.objects.get(model=c_type) File "D:\GitHub\Portfolio\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "D:\GitHub\Portfolio\lib\site-packages\django\db\models\query.py", line 429, in get raise self.model.DoesNotExist( Exception Type: DoesNotExist at /comments/11/ Exception Value: ContentType matching query does not exist. And its associated code in views.py: def comment_thread(request, pk): obj = get_object_or_404(Comment, pk=pk) content_object = obj.content_object # post that the comment is on content_id = obj.content_object.id initial_data = { 'content_type': obj.content_type, 'object_id': obj.object_id } form = CommentForm(request.POST or None, initial = initial_data) if form.is_valid(): c_type = form.cleaned_data.get('content_type') content_type = ContentType.objects.get(model=c_type) object_id = form.cleaned_data.get('object_id') body = form.cleaned_data.get('body') parent_obj = None try: parent_id = int(request.POST.get('parent_id')) except: parent_id = None if parent_id: parent_queryset = Comment.objects.filter(id=parent_id) if parent_queryset.exists() and parent_queryset.count() == 1: parent_obj = parent_queryset.first() comment, created = Comment.objects.get_or_create( user=request.user, content_type=content_type, object_id=object_id, body=body, parent=parent_obj ) return HttpResponseRedirect(obj.get_absolute_url()) context = { 'comment': obj, 'form': form, } return render(request, 'comments/comment_thread.html', context) If I replace content_type = ContentType.objects.get(model=c_type) with content_type = ContentType.objects.get_for_model(Blog) it … -
How to replace celery task with azure service bus in a django application?
I am asked to use the azure service bus instead of celery in a Django application. Read the documentation provided but didn't get a clear picture of using service bus instead of a celery task. Any advice provided would be of great help. -
Loggin users in using Django AuthenticationForm
I am trying to use the AuthenticationForm class to log users into my Django application. Here is my login_view in views.py: def login_view(request): form = AuthenticationForm(request.POST) if form.is_valid(): username = form.cleaned_data["username"] password = form.cleaned_data["password"] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return HttpResponseRedirect(reverse("users:index")) else: # form is invalid: return render(request, "users/login.html", {"message": "Invalid credentials."}) The above code does not work and always results in an "Invalid credentials" message. What am I doing wrong? -
Using a junction table in SQLite
I tried to find a solution on the internet but found just one tutorial which didn't help me that much. So here's my problem: I have a database that stores recipes but in different tables. E.g. one stores the title and the id, another stores the different preparations with the id, and the last one stores the ingredients and also each id. And to use it in Django properly I think I have to create a junction table, so I can use the database in Django from one model. I think I know how to create a junction table but I have no idea how to express on the one hand the OneToMany-relationship and on the other hand the ManyToMany-relationship(ingredients). So, I hope that you can either tell me another way of using it in Django right or you can help me creating the junction table -
Why is my css in Django app gets altered when I deploy my app on Heroku
I have created a website using Django and deployed it using Heroku..The problem is that size of divs and text which I have specified in my css files gets increased..On the other hand when I run the project on localhost the sizes and margins remain what I want..Why is this difference in size between localhost and actual website taking place? This is the link of my website -
Django Rest Framework - how to deal with data counting?
I have django app with django rest framework, that shows data from one table. It's very simple, when I enter url: http://127.0.0.1:8000/api/data/28/ it shows data that has dataset_id set to 28. However with a large amount of data it takes long time - even I can get 504. I looked into sql queries and found out, that there is this query: SELECT COUNT(*) AS "__count" FROM "my_table" WHERE "my_table"."dataset_id" = 28 that takes most of a time (like 50 sec), and second query, that actualy loades data: SELECT "my_table"."id", "my_table"."dataset_id", "my_table"."timestamp", "my_table"."data", FROM "my_table" WHERE "my_table"."dataset_id" = 28 ORDER BY "my_table"."timestamp" DESC LIMIT 25 and this query takes only 7 sec. Do you have any idea how to optimalize this? My idea is to somehow skip the first query, but still I need to know how many pages of data I have (just to not look blindly and get 404), so I don't know if it can be completely omitted. -
How to validate a django modelform if the form has some other fields
I have made a django model form but the problem is in my logic I am using something else and now I want to figure out a way to validate it by either defining a Meta class and choosing the fields that I want to display to the user but of course this won't validate the form. Now I want to know if there is a way to validate the form without touching the models and pass the data required for the logic and after take care of the information needed for the data of the model to be save Here is the models: from django.db import models from django.db import models from django.contrib.auth.models import User # Create your models here. class RoomCategory(models.Model): name = models.CharField(max_length=59) price = models.IntegerField() beds = models.PositiveIntegerField() capacity = models.PositiveIntegerField() size = models.CharField(max_length=59) def __str__(self): return self.name class Room(models.Model): room_number = models.CharField(max_length=60) room_category = models.ForeignKey(RoomCategory, on_delete=models.CASCADE) def __str__(self): return f"The room {self.room_number} {self.room_category} has a maximum of {self.room_category.capacity} person and cost {self.room_category.price}/night " class Booking(models.Model): customer = models.ForeignKey(User, on_delete=models.CASCADE) room = models.ForeignKey(RoomCategory, on_delete=models.CASCADE) check_in = models.DateField() check_out = models.DateField() adults = models.PositiveSmallIntegerField() children = models.PositiveSmallIntegerField() def __str__(self): return f"{self.customer} has booked for {self.room} from {self.check_in} … -
subprocess.call nohup & - doesn't run process in background
I have a function (Django admin) that runs Scrapy spider. The function works correctly. What I'm trying to do now is to make it non-blocking. This works as expected - I need to wait for the finish of SH SCRIPT. So basically I click on this action and browser is waiting for the end of crawling. subprocess.call([settings.CRAWL_SH_ABS_PATH, "db_profiles_spider", "ids", ids]) I want it to be non-blocking so the browser refreshes immediately. I tried this: subprocess.call(["nohup",settings.CRAWL_SH_ABS_PATH, "db_profiles_spider", "ids", ids, '&']) But it seems to be blocking and browser waits for the response. Why? How can I make it work? -
How to handle dynamically added variables in Django template
I am attempting to build a Django template that dynamically handles variables that may or may not exist. Here is the type of pattern I am using: {% block unsubscribe %} {% if unsubscribe_uuid is not None %} <a href="http://www.example.com/core/unsubscribe/{{ unsubscribe_uuid }}/" style=" font-size: .9em; color: rgba(255, 255, 255, 0.5);"> unsubscribe</a> | {% endif %} {% endblock %} This throws an error/exception/warning: django.template.base.VariableDoesNotExist: Failed lookup for key [unsubscribe_uuid] I've also tried checking with this line to check for the variable: {% if unsubscribe_uuid %} How can I check for variables in my template without throwing this error if they don't exists? -
How to update an arrayfield column in Django?
I have a column called errors in my table that is defined as ArrayField(models.IntegerField(default=0), default=list, null=True). The following is the updation that I'm doing to my table in a for loop over 100 iterations. testcase = Table1.objects.filter(ID=id,serialno ='1234', condition='False').select_for_update().update(condition='True', errors=iter_val) iter_val is an integer which is returned from the number of iterations in the for loop. I need the errors field to have an entry like [3,45,67,68,70,89]. But .update doesn't seem to append the integers to the array. How do I append the values to the arrayfield over a loop? -
why Django nginx server is not working when no requests are sent?
I don't know much about the nginx server. So, I have a doubt why it is not working as localserver used while making a django project. I have googled about this issue in different ways but it is of no use. So, kindly explain this to me. -
Namespacing DateArchiveView Url Django
Im trying to reference a date_based url archives such as WeekArchiveView,MonthArchiveView.When i hardcode the url its working ,but when i reference i have an error.I know there something am missing during referecing. VIEWS class MonthlySales(MonthArchiveView): queryset=Product.objects.all() date_field='date_purchased' allow_empty=True; class WeeklySales(WeekArchiveView): queryset=Product.objects.all() date_field='date_purchased' week_format ='%W' allow_empty=True; URLS url(r'^(?P<year>[0-9]{4})/week/(?P<week>[0-9]+)/$',views.WeeklySales.as_view(),name="weekly-sales"), url(r'^(?P<year>[0-9]{4})/(?P<month>[-\w]+)/$',views.MonthlySales.as_view(),name="monthly-sales"), REFERENCING IN HTML <a class="nav-link" href="{% url 'pos:monthly-sales'%}">Monthly sales</a> <a class="nav-link" href="{% url 'pos:weekly-sales'%}">Weekly Sales</a> Any assistance will be appreciated. Thankyou in advance -
The view user.views.profile didn't return an HttpResponse object. It returned None instead
views.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from .forms import UpdateUserForms, ProfileUpdateForm from django.contrib import messages # Create your views here. @login_required def profile(request): if request.method == 'POST': u_form = UpdateUserForms(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account is updated!') return redirect('profile') else: u_form = UpdateUserForms(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form } return render(request, 'profile.html', context) The view user.views.profile didn't return an HttpResponse object. It returned None instead. this error is occuring