Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I extend and Add extra views and urls, in the default Django Oscar restful API?
Django oscar does not provide a user registration API, so I am trying to add an API, for it. so that I can access the register API, from API root the same way I am accessing other APIs provided by oscar. Django 2.2.10 django-oscar 2.0.2 django-oscar-api 2.0.2 What I tried: urls.py(root) #OSCAR DEFAULT RESTful JSON API path("api/", include("oscarapi.urls")), apps.py class OscarAPIConfig(AppConfig): name = 'oscarapi' def ready(self): super().ready() def get_urls(self): urls = super().get_urls() urls += [ url(r'^register/$', views.UserCreateAPIView.as_view()), ] return self.post_process_urls(urls) views.py class UserCreateAPIView(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = RegistrationSerializer permission_classes = (AllowAny,) urls.py router = routers.DefaultRouter() router.register('users', views.UserCreateAPIView) urlpatterns = [ # url(r'^register/$', UserCreateAPIView.as_view()), path(r'^', include(router.urls)), ] -
Django i18n translations not working in production (Heroku)
My translations are working locally, but in production at Heroku, my site remains in its default language (English) after changing the language. These are in my settings.py file: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) USE_I18N = True USE_L10N = True LOCALE_PATHS = [os.path.join(BASE_DIR, 'locale')] This is my structure: myproject βββ Procfile βββ locale β βββ fr β βββ LC_MESSAGES β βββ django.mo β βββ django.po βββ myproject β βββ __init__.py β βββ settings.py I thought it was a path issue so I SSH'd into my Heroku app and printed LOCALE_PATHS: >>> from myproject.settings import LOCALE_PATHS >>> print(LOCALE_PATHS) ['/app/locale'] And pwd in locale/ returns pwd /app/locale. What did I do wrong? -
Django when clicked show another model attribute
I'm trying to make window where some text will be shown in one language, when clicked second language will appear. I've created one model which consists every information about post. model.py from django.db import models from datetime import datetime from django.contrib.auth.models import User def get_default_user(): return User.objects.get(id=1) class EveryPost(models.Model): title_pl = models.CharField(max_length=100, blank=True) title_ru = models.CharField(max_length=100, blank=True) text_pl = models.TextField(blank=True) text_ru = models.TextField(blank=True) date = models.DateTimeField(default=datetime.now, blank=True) User = models.ForeignKey(User, on_delete=models.CASCADE, default=get_default_user) def __str__(self): return self.title_pl html {% for obj in EveryPost %} <div class="card text-center"> <div class="card-header"> <ul class="nav nav-tabs card-header-tabs"> <li class="nav-item"> <a class="nav-link nav-main" href="{% url 'rupl' obj.pk %}">PL</a> </li> <li class="nav-item"> <a class="nav-link nav-main" href="{% url 'plru' obj.pk %}">RU</a> </li> </ul> </div> <div class="card-body"> <h5 class="card-title"><a href="{% url 'detailpost' obj.pk %}">{{ obj.title_pl }}</a></h5> <p class="card-text">{{ obj.text_pl|truncatechars:350 }}</p> <a href="{% url 'detailpost' obj.pk %}" class="btn btn-dark float-right">Zobacz </a> </div> <div class="card-footer text-muted"> <span class="float-left">{{ obj.date|date:"d M y" }}</span> <span class="float-right">PrzesΕane przez: {{ obj.User }}</span> </div> </div> {% endfor %} I've tried to make switch between text_pl and text_ru but it wasn't a good idea(lost data) views.py def plru(request, pk): post = EveryPost.objects.get(pk=pk) post.text_pl = post.text_ru post.title_pl = post.title_ru post.save() return redirect('index') def rupl(request, pk): post = EveryPost.objects.get(pk=pk) β¦ -
Implementing Json schema in my django restframework
I'm new in DJango and I'm trying to Implement a log collector system, which gets logs in Json format from different systems. My first challenge is that these systems generate different fields and I don't know how to define dynamic fields in my model for storing logs in my database which is PostGre. I mean that my json files define various fields in each request, so I can't use a single model for this purpose. The second challenge is that before arrival of Json log, a scheme will be sent to system to define my Json files properties as follows. My question is that, how I can implement such a system to get these data and help me with storing Json files when they arrive?: { namespace: βstringβ, schema: { field_1: type1, field_2: type2, β¦ } } "namespace" defines a specific structure in my system cause my system's clients can send multiple log types to my log collector. Thank you for your time. -
How to get current url in django views using selenium?
I want to automatically enter text in text area and click submit button after that. I'm trying to do this using selenium. The function inside views.py is not able to fetch current url. How can I achieve this? -
Whitenoise moduleerror not found
whitenoice is installed in my modules list, it's in my requirements.txt list and when I print help('modules') its also listed there. I've tried so many solutions online but none of them seem to work. -
Django i18n_patterns default language
I am using i18n_patterns to change the language prefix. It s working fine ones the language cookie was set. The problem is that it's adding /en/ when I trying to access a page without the language code in private window, even though my preferred language is not en (the default one set in settings.LANGUAGE_CODE). I have found how Django discovers language prefference First, it looks for the language prefix in the requested URL.Failing that, it looks for the LANGUAGE_SESSION_KEY key in the current userβs session.Failing that, it looks for a cookie. The name of the cookie used is set by the LANGUAGE_COOKIE_NAME setting. (The default name is django_language.) Failing that, it looks at the Accept-Language HTTP header. This header is sent by your browser and tells the server which language(s) you prefer, in order by priority. Django tries each language in the header until it finds one with available translations. Failing that, it uses the global LANGUAGE_CODE setting. So the reason why I get /en/ prefix in my url, when there is no any cookie set is because of the Accept-Language HTTP header. How can i solve that if somebody visits my site for the first time when there is β¦ -
Django: different access types for different urls
In my Django project, I defined my URLs in urls.py file as below: from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^api/', include('page1.urls')), url(r'^api/', include('page2.urls')), url(r'^remote/', include('registering.urls')), ] with ALLOWED_HOSTS definition in settings.py file, both /remote and /api has the same access from type, so if ALLOWED_HOSTS is ALLOWED_HOSTS = ['*'] So both /api and /remote URLs are remotely accessible. But if ALLOWED_HOSTS is: ALLOWED_HOSTS = ['localhost'] So both /api and /remote URLs are not remotely accessible, and are accessible only from localhost. But what I need is that only /remote URLs are remotely accessible. And /api should be accessible only from localhost and not allowed to access from remote. I there an idea to achieve that? -
Process not completed due to timeout error
I have the following code which copies content from already existing app to another slots keeping in mind that only new data gets added. However, I have optimized the code as I could. But, is it possible that can we do it with a bulk query as this code leads to django timeout error. if request.POST: app_ids=request.POST.getlist('app_ids') app = Client.objects.filter(id__in=app_ids) game_ids = json.loads(request.POST['game_ids']) for from_app_id in game_ids: from_label = Label.objects.get(id=from_app_id) if from_label.uigamelabel_set.all(): #if its a day label from_uidaylabel = from_label.uigamelabel_set.all().latest('id') from_slots = Schedule.objects.filter(label=from_label) from_label_playlists = Playlist.objects.filter(schedule__in=from_slots).distinct() for client in app: to_label = [] if len(client.playlists.filter(id__in=from_label_playlists)) != len(from_label_playlists): from_pl = set(list(from_label_playlists.order_by('id').values_list('id',flat=True))) to_pl = set(list(client.playlists.filter(id__in=from_label_playlists).order_by('id').values_list('id',flat=True))) diff_pl = list(from_pl - to_pl) for pl in Playlist.objects.filter(id__in=diff_pl): client.playlists.add(pl) client.save() client_day_labels = client.label_set.filter(uidaylabel__day__exact=from_uidaylabel.day) if client_day_labels: to_label = client_day_labels.latest('id') else: new_label_for_day = Label(text=from_label.text,style=from_label.style,client=client) new_label_for_day.save(saveToCouch=False) if not DayLabelMap.objects.filter(day__exact=from_uidaylabel.day,client=client).exists(): DayLabelMap.objects.create(label = new_label_for_day,day=from_uidaylabel.day,client=client) to_daylabelmap = DayLabelMap.objects.filter(day__exact=from_uidaylabel.day,client=client) to_daylabelmap = to_daylabelmap.latest('id') if to_daylabelmap.label.id != new_label_for_day.id: to_daylabelmap.label = new_label_for_day to_daylabelmap.save() to_uidaylabelmap = UiDayLabel(label=new_label_for_day,day=to_daylabelmap.day,client=client) to_uidaylabelmap.save() to_label = new_label_for_day if to_label: copyAppToAnother(from_label.id,to_label.id) -
How to make multiple template tags work separately?
While working on a project on django , I came to a situation where I have to join four strings and also have to save the joined string in another variable. So, I made two custom template tag to do so. 1) for saving one data to another @register.simple_tag def save(value): return value 2)to join the strings @register.simple_tag def link(a,b,c,d): data=str(a)+","+str(b)+str(c)+","+str(d) return data but when I am calling them from template like- {% save link 14 12 2 3 as data %} an error occurred saying-- 'save' received too many positional arguments that means they are overlapping each other. Now how to resolve this issue? -
Why has my Heroku celery stopped working?
I have a free Hobby django project using postgres and redis. I have 2 free dynos working with ON as status and its worked fine since deployment for 2 days until today. I have 2 periodic tasks there, one runs daily and other runs every 15mims. Anyone's got any idea why it did stop working? It should have run a task today already and didn't, but yesterday it was fine. -
What is the difference between the two Django post_save signals
I'm confused between why some tutorials and guides write two different post_save signal like below @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() when the profile can be saved by by calling the save() method in one approach itself @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: profile = Profile(user=instance) profile.save() -
"Field 'id' expected a number but got 'ashutoshmishra333@gmail.com'.",
while posting through postman getting error("Field 'id' expected a number but got '*********333@gmail.com'.",) my view set class PasswordViewSet(viewsets.ViewSet): def create(self, request): try: email = request.data.get('email') password = request.data.get('password') otp = request.data.get('otp') #user_obj = MyUser.objects.filter(email=email) otp_obj_check = Otp.objects.filter(email=email) user_obj=MyUser.objects.get(email=email) if not user_obj: raise Exception("email does not exist") if otp_obj_check: otp_obj = Otp.objects.filter(email=email).order_by('-id')[0] else: raise Exception("invalid otp") if not otp: raise Exception("please enter otp") if int(otp_obj.otp) == int(otp): for user_obj in user_obj: user_obj.set_password(password) user_obj.save() # token = get_access_token(user_obj) else: raise Exception('wrong otp') if not password: raise Exception('please enter password') return Response({"password": 'updated', "success": True}, status=status.HTTP_200_OK) except Exception as error: traceback.print_exc() return Response({"message": str(error), "success": False}, status=status.HTTP_200_OK) my model class Otp(models.Model): email=models.ForeignKey(MyUser,on_delete=models.CASCADE) otp=models.CharField(max_length=10,null=True,blank=True) def __str__(self): return self.otp -
Django - forms - force user fill in nullable fields in form
I've got a profile model with some nullable fields in order to create it easily, however, I'd like users to fill in all the form fields even if they are nullable when they try to edit it. Feel free to let me know if you need more info... Thanks!! -
Django auto increment model
I design Django Model as shown below : ` class User(models.Model): id-models.AutoField(primary_key=True) username=models.CharField(max_length=25,verbose_name="username") name=models.CharField(max_length=20,default="noName",verbose_name="name") password=models.CharField(max_length=20,verbose_name="password") email=models.EmailField() userCode=models.CharField(default=" ",max_length=100,verbose_name="User Code") def __str__(self): return self.username class Meta: ordering = ['-username']` Then I create an object in view.py. Although id is auto incremented, python want me to define an id. View.py is shown below. def register(request,id): if request.method=='POST': form = RegisterForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] name=form.cleaned_data["name"] password = form.cleaned_data["password"] email=form.cleaned_data.get("email") newUser = User(1,username,name,password,email) newUser.save() return redirect('mainPage') else: form=RegisterForm() context = { "form" : form, "id":id } return render(request,"SignupLogin.html",context) User(1,username,name,password,email) in that line, 1 is the id number. When I delete it, error which is about missing variable id, is thrown. How can I get rid of 1? -
I was trying to deploy my python and django project on heroku and facing this error in log files
2020-02-21T05:05:20.221933+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=bollymovierecommender.herokuapp.com request_id=caa9375b-25d0-4f7b-8049-f308bd5dc83e fwd="49.207.108.233" dyno= connect= service= status=503 bytes= protocol=https 2020-02-21T05:05:21.521664+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=bollymovierecommender.herokuapp.com request_id=67596e3f-cd06-479e-aa31-7e0fcf5a879b fwd="49.207.108.233" dyno= connect= service= status=503 bytes= protocol=https Can anyone help me understand what is this error? -
Django - Can I use django dump for a table that is auto generated by script?
I have this single table created from a script. And I need to migrate that table to another db server. Can I still use django dump directly or do I have to create a model for that table. -
Django framework with websocket
Iam working in django 2 with websockets inorder to pass the response to and fro a game server.Can anyone suggest the method or the correct flow for complete the communiction task between server and django through websockets? -
matching query does not exist Django
thanks for your time. i've just created a model that is linked to each user although i'm not beeing able to get objects from that model for the id or any other fields from his. I'm having trouble to when try to call each user.Parceiros.object when i try the Parceiros.objects.get(id=1) on python shell or in the project i get query does not exist. althgough if i try Parceiros.objects.filter(id=1) it gets me the object wanted. and getting this error:parceirosview() got an unexpected keyword argument 'id' views.py (i've tried both): def parceirosview(request, pk): parc = get_object_or_404(Parceiros, id=pk) context = {'parc': parc} return render(request, 'parceiro.html', context) def get_queryset(self): return super().get_queryset().filter(parceiro__user=self.request.user) models.py: get_user_model = User class Parceiros (models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) nome = models.CharField(max_length=200) endereco = models.TextField(max_length=400, blank=True) responsavel = models.CharField(max_length=100) tel = PhoneField(max_length=12) created_at = models.DateTimeField(auto_now=True) updated_at = models.DateTimeField(auto_now_add=True, blank=True) ativo = models.BooleanField(default=False) def __str__(self): return '%s %s' % (self.user, self.nome) def get_queryset(self): queryset = super(Parceiros, self).get_queryset() return queryset -
Notifying clients about an event via DRF
I want to know if there really is a way of notifying clients about a certain event, VIA Djangorestframework. I know it can be achieved with websockets via channels, but I couldn't find any material that explains everything in a step by step process. If anyone can help me than thanks already. -
Debug =True didn't work on production site
I have a project deployed on production with gunicorn and nginx (may be info about environment will help to answer on my question). While building some new functionality i want to see full errors traceback. In settings.py i switched debug=True also i have specified ALLOWED_HOSTS=['host.com','ip_adress'] but this mode isn't work. I expect that when i open 404 page i should see traceback. I know that enabling debug to true on production isn't a good way. But i need it. -
Django: how to add a product in function based view in restapi
In my company, i suggested to my co-developer to use 'generic-class' based view to add,update product but my senior developer said that to use 'function' based view and also use raw query instead of ORM, fetch data from sql db instead of define the schema in my models. i think this is very lengthy process, i am too much confused about how to start. here is my views to show list of item, but i am confused about how can i add and update item. import MySQLdb from pro.settings import connection cur, conn = connection() class Product_ListAPIView(APIView): def get(self,request,format=None): cur,conn = connection() query = ''' SELECT * FROM product_images ''' with conn.cursor(MySQLdb.cursors.DictCursor) as cursor: cursor.execute(query) result = cursor.fetchall() data = list(result) print(request.data) return Response({"product_data":result},status=status.HTTP_200_OK) # except Exception as e: # return Response({"data":"except block"}) it would be great if anyone suggest me for any helpful tutorial or could give me any helpful information then would be much appreciated. thank you! -
how to integrate interactive graphs in Django application with the current js libraries?
If D3.js, Chart.js, Plotly and NVD3.js then why ? what are the other better option for showing the manipulated data when we want to integrate data analytics and web development in a single web application. I have gone through the following links. Let me know the best and well documented analytical library for data visualization. -
Postgre SQL ignore the filtering condition if the value is null
I have the following three variables passed to the query A,B and C. A, B and C can take any values including null. When I run the below queryset, it should ignore the condition if the value in A,B or C is null queryset = User.objects.values().filter(A_name=A, B_name=B, C_name =C) For example, if C value passed in null then the query should behave like queryset = User.objects.values().filter(A_name=A, B_name=B) And if C and A value passed in null then the query should behave like queryset = User.objects.values().filter(B_name=B) I dont want to write all the 9 combinations and write a query. Is there any way I can do it easily?. -
How do I ensure that null fields are not inserted in mongodb, from django, using djongo connector?
I'm sharing a dummy code, expecting myself to be as clear as possible. 1. I have a model like this from django.db.models import Model, CharField, IntegerField, DateField class Account(Model): name = CharField(max_length=30, null=False, blank=False, unique=True, default=None) rank = IntegerField(null=True, blank=True, default=None) date = DateField(null=True, blank=True, default=None) 2. I have my DB settings in django like this DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'TEST', 'HOST': 'localhost' } } 3. After running model migration commands, in the django shell, I added two objects(documents) to the configured TEST DB like this In [1]: from dummy.models import Account In [2]: Account.objects.create(name="Sai") Out[2]: <Account: Sai> In [3]: Account.objects.create(name="Ravi", rank=1) Out[3]: <Account: Ravi> 4. When I check in Mongodb CLI, I'm getting the null values as well as null > db.dummy_account.find().pretty(); { "_id" : ObjectId("5e4f54939069175d6ed7890e"), "id" : 1, "name" : "Sai", "rank" : null, "date" : null } { "_id" : ObjectId("5e4f54a89069175d6ed7890f"), "id" : 2, "name" : "Ravi", "rank" : 1, "date" : null } Q. (Fields that have null should not be stored) What do I need to do to get my expected result like this? > db.dummy_account.find().pretty(); { "_id" : ObjectId("5e4f54939069175d6ed7890e"), "id" : 1, "name" : "Sai" } { "_id" : ObjectId("5e4f54a89069175d6ed7890f"), β¦