Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change the parameter dynamically in pd.DateOffset in python code?
date_ranges_values = request.POST['range'] ft = [df.index[-1]+ DateOffset(date_ranges_values =lambda x:x)for x in range(0,24))] -
How can I resolve the dist/css/404 error locally in django?
Attempting to upload a dist file built with vue to python backend. I set the structure like this in the django. /backend/shopee/base.py STATIC_URL = "/dist/" STATIC_ROOT = ( os.path.dirname(Path(__file__).resolve().parent.parent.parent) + "/frontend/dist/" ) DEBUG = True INSTALLED_APPS = [ "frontend.dist", ... ] FRONTEND_DIR = ( os.path.dirname(Path(__file__).resolve().parent.parent.parent) + "/frontend" ) TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [os.path.join(FRONTEND_DIR, "dist")], "APP_DIRS": True, "OPTIONS": { "context_processors": [ ... ], }, }, ] and urls.py urlpatterns = [ path("", index, name="index"), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) If runserver is set in this way, an error occurs in localhost/8000. Did I make a mistake? -
how to just access the count of products through another model which are connected by foreign key
class Category(models.Model): category_name = models.CharField(max_length=50, unique=True) class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) product_name = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) Here what i want is just the number of the product present in each category just the number of product i know i have can fire somequery cat = Category.objects.all() run loop for cat prod_cat = Product.object.filter(category=cat) But i belive its not the efficient way to achive this -
Generating elements in Django from Python list
Im havin trouble generating elements from a for loop via iteration of a py list in Django. Using Metro UI as front end framework. import os img_dir = os.listdir("static/img/sasha_banks") #print(img_dir) # <img src="{% static 'img/sasha_banks/sasha_banks5.jpg' %}"> def sasha_files(): sasha_dir = [] for img in img_dir: sasha_dir.append(f'img/sasha_banks/{img}') print(sasha_dir) sasha_files() Above python script works i jist cant seem to get to that sasha_dir list. The commented was the hard coded django that works, im just trying to read the directory, pushthe filepath and concat the files in dir and then iterate that list to create -
Update None values in django Database
I have field in django model city which stored None but i want to update it how can i update the field data with respect to user id I tried a=Model.objects.filter(id=1).update(City = 'Vatican') this returned 1 -
Syndication Feed View RSS to File
I'm using django as my web frontend for my podcast. I use a CDN for hosting all my media, and lately I have wanted that same CDN to host my RSS Feed, not directly django. The current setup has some basic well known primitives: path('podcast.xml', SubscribeFeed(), name='episode_feed'), Some additional context; SubscribeFeed is a Syndication Feed (https://github.com/django/django/blob/main/django/contrib/syndication/views.py#L27) that is based off of the https://docs.djangoproject.com/en/4.0/ref/contrib/syndication/#custom-feed-generators And it looks somewhat like: class iTunesFeed(Rss201rev2Feed): content_type = 'application/xml; charset=utf-8' def root_attributes(self): attrs = super().root_attributes() attrs['xmlns:itunes'] = 'http://www.itunes.com/dtds/podcast-1.0.dtd' return attrs < ... Ripped right from the custom feed generators with a ton of extra elements for the specific podcast category and such ... > class SubscribeFeed(Feed): title = "My Cool Podcast" description = About.objects.first().about author_email = "podcast@gmail.com" author_name = "John Doe" feed_type = iTunesFeed def item_pubdate(self, item): return item.pub_date < ... More stuff that isn't relevant ... > Just to be clear this view works perfectly with Django serving the podcast RSS. It works in all major platforms and is very nice. My problem/question is that: I want to generate/render this view to a text file, the purpose being; I host media on a CDN, I would also benefit myself to put this RSS Feed on … -
Django update_or_create using foreying key objects
My app have two models, PortfolioAsset and Transction. I am trying to use update_or_create in the transaction to find if the object PortfolioAsset exist with the selected parameters. If it exist to update, if not to create. But i am getting this error: Cannot assign "(<PortfolioAsset: PortfolioAsset object (11)>, False)": "Transaction.portfolio_asset" must be a "PortfolioAsset" instance. This was the exisiting object that i would like to update in this example. PortfolioAsset class PortfolioAsset(models.Model): portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE, default=1) asset = models.ForeignKey(Asset, on_delete=models.CASCADE) shares_amount = models.DecimalField(max_digits=18, decimal_places=0) def validate_unique(self, *args, **kwargs): super().validate_unique(*args, **kwargs) if self.__class__.objects.\ filter(portfolio=self.portfolio, asset=self.asset).\ exists(): raise ValidationError( message='This asset already exists in this portfolio.', code='unique_together', ) and Transactions: class Transaction(models.Model): OrderChoices = ( ('Buy', 'Buy'), ('Sell', 'Sell'), ) portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE, default=1) asset = models.ForeignKey(Asset, on_delete=models.CASCADE, default=1) portfolio_asset = models.ForeignKey(PortfolioAsset, on_delete=models.CASCADE, editable=False) shares_amount = models.DecimalField(max_digits=18, decimal_places=0) order = models.CharField(max_length = 8, choices = OrderChoices) def save(self, *args, **kwargs): self.portfolio_asset = PortfolioAsset.objects.update_or_create(portfolio=self.portfolio, asset=self.asset) if self.order == 'Buy': self.portfolio_asset.shares_amount += self.shares_amount if self.order == 'Sell': self.portfolio_asset.shares_amount -= self.shares_amount self.portfolio_asset.save() super(Transaction, self).save(*args, **kwargs) What am i doing wrong? Thanks -
CSRF cookie error after Django 3.2 update (DRF with token authentication)
I was looking to update my app backend from Django 3.1.14 (working fine but no longer supported) to a newer version (I tried both 3.2 and 4.0), but after updating I started getting a CSRF cookie error. Forbidden (CSRF cookie not set.): /api-token-auth/ Does anybody by any chance know what's changed in Django in regard to CSRF, and how to avoid the errors? I was under the impression that CSRF is not enforced when using Django Rest Framework with token authentication. I tried anyway to remove the 'django.middleware.csrf.CsrfViewMiddleware' middleware, to add @csrf_exempt to all the views, deleted all existing tokens and logged out of Django admin, but to no avail. My DRF configuration in settings.py is as follows: INSTALLED_APPS = [ 'rest_framework', 'rest_framework.authtoken', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } -
Using Django-Taggit in Django Rest Framework 3.13.1 with Django 4.0.2 with Error "Invalid json list" in Serializing Tags Model Attribute
Older solutions uses django-taggit-serializer which is now been deprecated and doesn't work with the version I have. I have already done what the documentation says regarding the integration with DRF. However, I am getting this error: b'{"tags":["Invalid json list. A tag list submitted in string form must be valid json."]}' image error in drf browsable api Here is my code viewset.py class AnnouncementViewSet(viewsets.ModelViewSet): """Announcement ViewSet.""" queryset = Announcement.objects.all() serializer_class = AnnouncementSerializer lookup_field = "slug" permission_classes = [IsAdminUser, IsAuthorOrReadOnly] def get_permissions(self): """Return permissions.""" if self.action in ["create", "update", "partial_update", "destroy"]: self.permission_classes = [IsAdminUser] else: self.permission_classes = [IsAuthorOrReadOnly] return super().get_permissions() models.py class Announcement(models.Model): """Announcement model.""" created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) title = models.CharField(_("title"), max_length=255, unique=True) content = models.TextField(_("content")) is_featured = models.BooleanField(default=False) thumbnail = models.ImageField( upload_to="announcement/thumbnail", default="announcement/thumbnail/default.jpg" ) tags = TaggableManager(_("tags")) slug = models.SlugField(_("Slug"), max_length=255, unique=True) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super().save(*args, **kwargs) serializers.py class AnnouncementSerializer(TaggitSerializer, serializers.ModelSerializer): tags = TagListSerializerField() class Meta: model = Announcement exclude = ["slug"] extra_kwargs = { "url": {"view_name": "api:announcement-detail", "lookup_field": "slug"} } What I have tried so far: tags = "my-tag" tags = ["tag1", "tag2"] I even wrote a test: tests.py def test_announcement_create_url( self, api_client: Client, admin_user ): api_client.force_login(admin_user) response = api_client.post( … -
Django check if many-to-many relationship exists
I have a kind of social network in Django where people can send direct messages. Within all of those messages, I have a conversation field to show who the messages are between so that I can group the messages by person when displaying them to the user. I'm trying to figure out how I can search for if a conversation exists. In the print statements below in the view, I get back: <QuerySet [<Conversation: Sarah and Stephen>, <Conversation: Sarah and James>]> <QuerySet [<User: Sarah>, <User: Stephen>]> <QuerySet [<User: Sarah>, <User: James>]> In the view below, the sender is 'Sarah' and the receiver is 'James', so I'm trying to figure out how I can search for if a conversation between them already exists (through filter or something) by matching them with the kinds of QuerySet lists above so that if so, I can use that conversation and if not, I can create the conversation. I've tried many things but keep getting stuck. I'm pretty new to many-to-many relationships. The view def writemessage(request, id): profile = Profile.objects.get(id=id) context = { 'profile': profile, } conversations = Conversation.objects.all() print(conversations) for each in conversations: print(each.participants.all()) if request.method == 'POST': sender = request.user receiver = profile.user … -
Search functionality works but not getting any results (django project)
I am currently working on my Django app and the search functionality is working but I am not getting a response on the site ( at pets.html is where the search form is located ). The URL looks right when a submit request is being sent and the keywords are visible in the URL. No errors in the console. Any help is greatly appreciated Here is the link to the repository: https://github.com/Amanuel763/Athenawebsite -
Django: dates not send properly in values tag
:) I send in context dates that want to use in chart labels, but every time when I use it in tag I get with "&#x" every begining and ending If I use it normally in HTML it work... -
Do I need to create both a web application and an api for it
I have this thought about restful api's. I use django for web development and i really want to know weather i should build both a django web application or a django restapi web application or both of them because i find it pretty confusing. -
DRF SocialLoginVeiw Custom? or Create New View?
class KAKAOLogin(SocialLoginView): adapter_class = KakaoOAuth2Adapter client_class = OAuth2Client serializer_class = SocialLoginSerializer def get_serializer(self, *args, **kwargs): serializer_class = self.get_serializer_class() kwargs['context'] = self.get_serializer_context() return serializer_class(*args, **kwargs) now i using Django allauth SocialLoginView. when Signin my app, i used Username (not email). but when i using SocialLoginView, enter username as "real name" or "user" to DB. In this case, I would like to know if it is better to create a new Login View and use it, or if it can be modified and used in the above code. what should i do? -
No reverse match. Ideas how to fix?
Can anyone figure out why I'm getting a no reverse match error here: urls.py: urlpatterns = [ path('', views.ReservationsFormView.as_view(), name='reservations'), path('edit/<slug:pk>/', EditReservationView.as_view(), name="edit_reservation"), path('reservation_complete/', ReservationCompleteView.as_view(), name="reservation_complete"), path('reservations_account/', ReservationAccountView.as_view(), name="reservations_account"), path('delete/<slug:pk>/', DeleteReservationView.as_view(), name="delete_reservation"), ] It's only happening, so far, on my edit/delete paths (the one's with the slug:pk) views.py: class ReservationsFormView(CreateView): model = Reservations template_name = "reservations/reservations.html" form_class = ReservationForm success_url = "reservation_complete/" def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) class EditReservationView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): form_class = ReservationForm template_name = 'reservations/edit_reservation.html' success_url = "/reservations_account/" model = Reservations def test_func(self): return self.request.user == self.get_object().user class ReservationCompleteView(CreateView): template_name = "reservations/reservation_complete.html" success_url = "/reservation_complete/" form_class = ReservationForm model = Reservations class ReservationAccountView(ListView): template_name = "reservations/reservations_account.html" model = Reservations def get_context_data(self, **kwargs): context = { 'reservations': self.model.objects.filter(user=self.request.user), } return context class DeleteReservationView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): """ A view to delete an reservation """ model = Reservations success_url = "/reservations_account/" def test_func(self): return self.request.user == self.get_object().user Corresponding Html is: <button href="{% url 'edit_reservation' reservation.id %}" type="button" class="btn btn-dark">Edit</a> <button href="{% url 'delete_reservation' reservation.id %}" type="button" class="btn btn-dark">Delete</a> Error Message: NoReverseMatch: Reverse for 'delete_reservation' with no arguments not found. 1 pattern(s) tried: ['reservations/delete/(?P[-a-zA-Z0-9_]+)/$'] Really hoping it's something simple. Any help is appreciated. If you need to see more … -
How to catch an empty query exception with Django
I'm after an elegant and efficient approach. I am doing a query to a model that has a chance to return an empty queryset and if that happens I must do a query with other parameters that will work for sure. It would be really nice if I could put the query inside a simple try except but it doesn't catch like so. What's holding me back from using .exists() is that it feels like I'm doing the query to the database two times. One to check the existence and the other to really get the object. -
Function failure after closing SSH in Django
I have written the below function in views.py to check whether the given mobile number is authorized or not @api_view(['POST']) def authorize_subscriber(request): if request.method == 'POST': data=request.POST str = "\"" authorization_data=ast.literal_eval(str.join(list(data.keys()))) try : sub = Subscription.objects.get(accountid=authorization_data["mobile"]) status_message={"message":"success","data": { "mobile": sub.accountid, "calling_code": "+91", "subscription_start_date": sub.subscriptionstartdate, "subscription_end_date": sub.subscriptionenddate } } error=status.HTTP_200_OK except : status_message={'message': 'Unauthorized Request'} error=status.HTTP_401_UNAUTHORIZED #print(status_message) return JsonResponse(data=status_message,status=error) This function is working fine when I use ssh to server and run Django server but it is failing when I exit ssh. If I exit the ssh except for this function all other functions are working fine. In request POST, I am getting the data as shown in the below format <QueryDict: {'{"mobile":"9160208253"}': ['']}> Below is my script which is used to run the Django server. user -k -n tcp 8085 cd /home/absott/.myplatform gunicorn --timeout 600 --bind 0.0.0.0:8085 myplatform.wsgi & Can anyone help me to fix this issue? -
Best way to reuse code from an old data migration in a new data migration
A few months ago, I wrote a custom data migration that created some model objects. I wrote a function inside the migration file, create_data, and then for the migration operation, ran it using RunPython operations = [ migrations.RunPython(create_data) ] Now, we have another object we need to be automatically populated by migrations. I'd like to reuse my create_data function, but in a new migration. Problem is, I don't know if I can import it properly, or if importing from a previous migration is a bad idea. create_data = __import__('projects.project.migrations.0012_auto_20210331_2126').create_data This doesn't work, but anyways I think there are issues importing from files that start with numbers that make this weird. The other idea I have is to copy paste this function into one of my normal django apps where reusable code lives, then I could import it as usual and use in future migrations without issue as well. The downside is that the code is still copy pasted once. How should I reuse my old code from this older migration in a new migration? Is there a nice way to import it, or should I just copy paste it to a better place and never put logic in migration files … -
How to modify all databases when overriding DiscoverRunner setup_databases with parallel
I'm running the tests with --parallel and want to add some object to every database that is created (for each process). currently, I have a CustomTestRunner which inherit from DiscoverRunner. In that class, I'm overriding setup_databases method. after calling super().setup_databases(), I'm making a change in the db (like Users.objects.create(....)) The changes occur only in one of the databases, But I want that change to be in all of them. How can I achieve that? My Custom Test Runner -
add help text for OneToOneField
I want to add a help_text to a field in my admin create for a model. I already tried what is suggested here. models.py: class Product(models.Model): name = ... ean = models.OneToOneField(EANCode, on_delete = models.CASCADE, help_text = "from model, not visible ...") forms.py: class ProductAdminForm(forms.ModelForm): class Meta: model = Product fields = '__all__' help_texts = {"name": "this is visible", "ean": "this is not visible"} So I can add a helptext to a CharField but not to a OneToOneField. Why? -
'“1” is not a valid UUID.' Django
Getting this error when i try to delete a reservation from a user account on my restuarant booking app. Tried a few things to no avail so if anyone can help I'd greatly apprecaite it. Code is as follows: class Reservations(models.Model): """ reservation form categories and attributes """ user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True) name = models.CharField(max_length=50) phone_number = models.CharField(validators=[phoneNumberRegex], max_length=16, unique=True) email = models.EmailField() date = models.DateField() time = models.CharField(choices=time_options, default="12pm", max_length=10) number_of_party = models.IntegerField(choices=party_size, default=1) reservation_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) Not sure where the 1 is even coming from in this instance. If you need to see more code ask and i'll edit the post. Thanks in advance. -
Problem with different divs size and infinity scroll
django/bootstrap/infinity scroll(https://infinite-scroll.com) I want to add infinity scroll to my news page. Queryset with 2 types of news, big(col-lg-8) and small(col-lg-4). Now I have problems with blocks (see example picture). How to make pagination page added to the previous page row? Example <div class="container"> <div class="article-feed"> <div class="row iscroll"> {% for art in all %} {% if art.banner_page %} <div class="col-lg-8 mb-2 mt-2"> <img class="card-img-top" src="{{art.banner.url}}" > </div> {% else %} div class="col-lg-4 mb-2 mt-2 "> <img class="card-img-top" src="{{art.banner.url}}" > </div> {% endif %}{% endfor %} <p class="pagination"> <a class="pagination__next" href="?page={{ page_obj.next_page_number }}"> </a></p> <script src="{% static "js/infinite-scroll.pkgd.min.js" %}"></script> <script> $('.article-feed').infiniteScroll({ path: '.pagination__next', append: '.iscroll', }); </script> -
how can I prepare and put Time series forecasting graph in html of Django project interactive by chartjs?
I want to make an interactive website where users can upload or input their data and get forecasting analysis result based on python Time series graphs. Is there a free python or javascript module for handling python graphs in django project? I pointed some modules like Chartjs but how can I show Time series analysis in something like chartjs? -
NOT NULL constraint failed: spring_post.publisher_id
I created a class base create view.When i try to submite the post model create view. it will return NOT NULL constraint failed: spring_post.publisher_id how can i set the publisher the get the current logged in user and set it to the post piblisher field. im a beginner this is the publisher field in my post model publisher=models.ForeignKey(User,on_delete=models.PROTECT) #and this is my views class PostCreateView(LoginRequiredMixin,CreateView): model=Post fields=['title','description'] redirect_field_name="login" -
Adding Data from Bootstrap Cards as Django Objects Using Checkboxes
This is kind of a complicated question, but: I am using Django. User enters data on one template and then using logic in my view and an API call, the next page is rendered which displays multiple bootstrap cards, each containing data from that API call present in that first view. On top of each bootstrap card holding the data is a checkbox. I would like to have the user be able to check/uncheck any bootstrap card to add the data from those cards as a new object (NewNFT from my models.py). In an attempt to make it less complicated, I will just share my html, which shows how each card is formatted with the text box/data from the API call and then I will also share my model for the object that is being created. Is anyone able to explain how to add each of these 'cards' (really data from each card) as a new object for my model? I can't figure out the view.py logic to make that happen. For some reason it's not letting me display, but of course there would be a form around the card data as well as a submit button. And the data …