Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do i run redis in background of deployed website just like i run redis server manually when on local host?
I have been using redis server on my windows for websocket programming in my chat project django. Now, the time of deployment has arrived and i do not know how to run the server on the deployed website. -
How to change browse button upload ImageField to drag drop upload on Django Admin
Currently I have inline list of photos like this : I wish to change the browse button as drag drop upload, does anyone can help to make it ? here is my current code : model.py class PlacePhoto(models.Model): name = models.CharField(max_length=30, blank=True, null=True, default="") original_photo = models.ImageField( 'photo', upload_to='place') photo = ImageSpecField( source='original_photo') thumbnail = ImageSpecField( source='original_photo') place = models.ForeignKey('Place', on_delete=models.CASCADE, related_name='place_photos') admin.py class PlacePhotoInline(admin.TabularInline): model = PlacePhoto extra = 1 fields = ('name', 'display_image', 'original_photo',) readonly_fields = ('display_image',) def display_image(self, obj): return mark_safe(f'<img src="{obj.original_photo.url}"' f' width="{300}" height={200} />') -
Does django's `save()` create or update?
The documentation just says To save an object back to the database, call save() That does not make it clear. Exprimenting, I found that if I include an id, it updates existing entry, while, if I don't, it creates a new row. Does the documentation specify what happens? -
Django localization form not swtiching
I am unable to switch languages using the example form provided in the Django docs. Translations are working if I manually change the URL language prefix. Settings.py LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LOCALE_PATHS = [ os.path.join(BASE_DIR, 'locale'), ] # Middleware 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', # Context Processors 'django.template.context_processors.i18n', urls.py urlpatterns = [ # Set language path('i18n/', include('django.conf.urls.i18n')), # Admin path('admin/', admin.site.urls), ] urlpatterns += i18n_patterns( path('test/', node_views.test), prefix_default_language=True, )+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) HTML {% load i18n %} {% trans "This is a test" %} <form action="{% url 'set_language' %}" method="post">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}"> <select name="language"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected{% endif %}> {{ language.name_local }} ({{ language.code }}) </option> {% endfor %} </select> <input type="submit" value="Go"> </form> The default form returns a 302 response to the same URL I am currently on without changing the language. The {{ redirect_to }} value in the form input does not contain a value, maybe this should be populated with something? I am … -
Send Angular PUT request to Django using Django CSRF
I am trying to update an entry into the django sqlite database using a put request. I am getting lots of 'forbidden' and '403' errors. I think this is because I can't find a way to attach the CSRF token from django. I have seen some previous answers on here but they are from much older versions of Angular and I can't figure how to edit them to work with my code. (saying to put them in the module.config() block which I can't find). Component HTML: <button class="btn btn-warning shadow-sm" (click)="update(project)">Update</button> Component TS: update(project: Project) { this.projectService.updateProject(project).subscribe(); } Service TS: updateProject(project: Project) { var httpudpdate: any = this.http.put('/ph/projects/'+project.id, project) return httpudpdate } I want the entry to be updated in the django but I am just getting errors, forbidden and 403. -
Cannot login django admin page in chrome
Unable to login in django admin page on chrome only. In previously work just fine. login with other browser like Safari and Firefox work like a charm. Can anybody please help me -
Update data while slow internet connection in Django rest api
Views.py class Bet(UpdateAPIView): """ Sample method """ def put(self, request, *args, **kwargs): instance = self.get_object() if request.data.get('i') == 1: #some code elif request.data.get('i') == 2: #some code elif request.data.get('i') == 3: #some code elif request.data.get('i') == 4: #some code else: ## a large block of code also **it create a new entry for request user and bet in 3-4 tables.** instance.user = request.user instance.save() return custom_render(status_code, message, response_status) Here two user(user1 and user2) are call the API at same time in slow internet connection. Now due to slow connection both api's passed all the validation and code execution reach to else block. and will create entry for both user. Here My problem is if any user accept the bet then nobody can accept the same bet. In fast internet connection, its working fine by checking request.data.get('i') == 1 True and return the response. -
Is there a better way to store a list of integers in a MySQL Model?
I'd like to store a list of integers in a MySQL field. My current workaround: import datetime from django.db import models class myModel(models.Model): testList = models.CharField() def set_testList(self,data): self.testList = ','.join(map(str, data)) def get_testList(self): return list(map(int, self.testField.split(','))) This works fine as long as I go through set_testList and get_testList to set and retrieve the field. This get particularly annoying as I have 4-5 such fields in some models, and having to set and retrieve every field through their own set and get methods makes the code much less readable and increases db queries. Is it possible to create a solution where I wouldn't have to go through custom methods to achieve this? The optimal case would be to set the field using: myModel.objects.create(testField=[1,2,3,4]); and retrieve it using myModelobjects.get(pk=1).values() and have the conversion occur 'behind the scenes'. Is something like this possible (without having to migrate to PostgreSQL)? -
Identify Django queryset from SQL logs
I use Django 1.8.17 (I know it's not so young anymore). I have logged slow requests on PostGres for more than one minute. I have a lot of trouble finding the Queryset to which the SQL query listed in the logs belongs. Is there an identifier that could be added to the Queryset to find the associated SQL query in the Logs or a trick to easily identify it? Here is an exemple of common Queryset almost impossible to identify as I have several similars ones. Queryset: Video.objects.filter(status='online').order_by('created') LOGs: duration: 1056.540 ms statement: SELECT "video"."id", "video"."title", "video"."description", "video"."duration", "video"."html_description", "video"."niche_id", "video"."owner_id", "video"."views", "video"."rating" FROM "video" WHERE "video"."status" = 'online' ORDER BY "video"."created" Desired LOGs: duration: 1056.540 ms statement: SELECT "video"."id", "video"."title", "video"."description", "video"."duration", "video"."html_description", "video"."niche_id", "video"."owner_id", "video"."views", "video"."rating" FROM "video" WHERE "video"."status" = 'online' ORDER BY "video"."created" (ID=555) -
Add Queryset to django updateview
I have an updateview in which a manager can go and edit all the fields for the associate. Looks like this:(requirement is to add associate_mgr in the as a dropdown in the updateview)enter image description here views.py class ReallocationTeam(LoginRequiredMixin,UpdateView): model = UserDetails form_class = ViewEditSample def get_success_url(self): return reverse('UserProfile:index') forms.py class ViewEditSample(ModelForm): class Meta: model = UserDetails fields = ['associate_name','client','lob','associate_mgr'] The manager should be able to edit the manager of that associate too. models.py associate_name = models.CharField(max_length=200) associate_nbr = models.CharField(max_length=8, primary_key=True) associate_email = models.EmailField() associate_department_id = models.CharField(max_length=50) associate_mgr = models.CharField(max_length=100,blank=True, null=True) associate_exec = models.CharField(max_length=100,blank=True, null=True) associate_org = models.CharField(max_length=100,blank=True,null=True) title = models.CharField(null=True, blank=True, max_length=100) date_of_service = models.CharField(null=True,blank=True,max_length=11) is_manager = models.BooleanField(default=False) is_exec = models.BooleanField(default=False) is_team_lead = models.BooleanField(default=False) model = UserDetails fields = ['associate_name','client','lob','associate_mgr'] but associate_mgr is not a choice field in my db. I need to add a dropdown that contains managers in my UpdateView. How do I go about implementing that? -
How to change Representation of Many to Many related object in Django Rest Framework
I want the complete related model on GET and use the id's on CREATE, UPDATE and DELETE. I try to use to_representation. So i want to create an array of dicts called users which should show the complete users. But i get the error "unhashable type: 'ReturnDict'" when i add the dict in the object, it works fine if i would do it for a single user by writing to the array directly. class CompanySerializer(serializers.ModelSerializer): #users = UserSerializer(many=True) created_at = serializers.DateTimeField() updated_at = serializers.DateTimeField() class Meta: model = Company fields = ['id', 'name', 'street', 'city', 'postal_code', 'state', 'company_form', 'users', 'created_at', 'updated_at'] def to_representation(self, instance): representation = super(CompanySerializer, self).to_representation(instance) representation['company_form'] = CompanyFormSerializer(instance.company_form).data representation['users'] = [] for entry in instance.users.all(): user = {UserSerializer(entry).data} representation['users'].extend(user) return representation -
invalid literal for int() with base 10: 'string name'
I am making an API module which saves weather data to my Django database by running a single Django management command, which retries all the data from a source API. I've created a model 'weather data' which has all the required datatypes. I've a management command written which directly saves data to my database. The snippet of management command and models.py is shown below. def handle(self,*args,**kwargs): for city in input_file: city_name = city.strip() print(city_name) full_api_url = api + city_name + '&mode=json&units=' + unit + '&APPID=' + user_api full_wet_url = weather_api + city_name + '&mode=json&units=' + unit + '&APPID=' + user_api try: data = requests.get(full_api_url).json() dta = requests.get(full_wet_url).json() city_id = dta["id"] longitude = dta["coord"]["lon"] latitude= dta["coord"]["lat"] for dt in data["list"]: temp = dt["main"]["temp"] temp_min = dt["main"]["temp_min"] temp_max = dt["main"]["temp_max"] pressure = dt["main"]["pressure"] sea_level = dt["main"]["sea_level"] grnd_level = dt["main"]["grnd_level"] humidity = dt["main"]["humidity"] weather = dt["weather"][0] main = weather["main"] description = weather["description"] clouds = dt["clouds"]["all"] wind_speed = dt["wind"]["speed"] wind_deg = dt["wind"]["deg"] dt_txt = dt["dt_txt"] wd = weatherdata(city_name,city_id,latitude,longitude,dt_txt,temp,temp_min,temp_max,pressure,sea_level,grnd_level,humidity,main,description,clouds,wind_speed,wind_deg).save() print ("Success") except Exception as e: print (e) pass class weatherdata(models.Model): city_name = models.CharField(max_length = 80) city_id = models.IntegerField(default=0) latitude = models.FloatField(null=True , blank=True) longitude = models.FloatField(null=True , blank=True) dt_txt = models.DateTimeField() temp = models.FloatField(null = … -
Build a custom View to give permissions to a specific User (not using ADMIN)
I want to build a custom view that gives ( or take depending on the situation) permission(s) to user. What I want to do is to produce a form with all the permissions listed with check boxes next to each permission, checked already against a permission given to user. In simpler words, I want to make the customised version of Django Admin where I can give or take back the permissions. How can I do this? I can get a list of permissions by using from django.contrib.auth.models import Permission per=Permission.objects.all() similarly I can get the user object by using user=User.objects.get(id=id) model. But how can I produce a form with which has check boxes and a view to connect all the checked/unchecked permissions to the user? -
Delete operation finding a relationship that doesn't exist
In my multi-tenant site, I have the following database structure: Public (shared): tenants domains users Test: users clients projects projectusers tasks Test2: users clients projects projectusers tasks This is a simplified list - all three schemas include (among others) auth_permissions, auth_group, and auth_group_permissions. The projectusers table (cross-ref that ties users to projects), has a One-to-One field for the User table, and a ForeignKey to the projects table, as follows: class ProjectUser(DateFieldsModelMixin, models.Model): user = models.OneToOneField( User, on_delete=models.PROTECT, verbose_name=_('User'), related_name='user_projects', ) project = models.ForeignKey( Project, on_delete=models.PROTECT, verbose_name=_('Project'), related_name='project_users', ) ...other fields omitted... The point is, the reference from projectusers to users is defined in the ProjectUser model. There's no reference from User model back to ProjectUser. I wrote a load_fixtures (management) command to, well, load fixtures to set up our dev site(s) with the data we'd need to do preliminary testing (before writing/running unit-tests). One of the things that command does is empty the auth_permissions table, reset the auto-increment value back to 1, and then import its fixture so that all IDs match across local dev sites, and (eventually) in production. This is necessary because fixtures for auth_group and auth_group_permissions reference permissions by ID. The error I'm getting occurs during the … -
Django REST framework - reverse ForeignKey relations
I have the following three models structured around the premise of the Survey. class Survey(models.Model): ... id = models.UUIDField(_('Id'), primary_key=True, default=uuid.uuid4, editable=False,) name = models.CharField(_('Name'), max_length=120, blank=True, unique=True) slug = models.SlugField(_('Slug'), max_length=120, blank=True, unique=True) description = models.TextField(_('Description'), blank=True) ... Each Survey can have multiple questions SurveyQuestion: class SurveyQuestion(models.Model): ... survey = models.ForeignKey('surveys.Survey', on_delete=models.CASCADE, null=True, blank=True,) And each SurveyQuestion can have multiple answers SurveyQuestionAnswer: class SurveyQuestionAnswer(models.Model): ... survey_question = models.ForeignKey('surveys.SurveyQuestion', on_delete=models.CASCADE, null=True, blank=True,) For the sake of brevity, imagine my Survey serializers as being as simple as possible: class SurveySerialializer(serializers.ModelSerializer): class Meta: model = Survey fields = ('__all__') Effectively, what I have is the following: class Survey(APIView): """ Survey GET request endpoint: fetches Survey """ permission_classes = User def get(self, request, survey_slug): survey = Survey.objects.get(slug=survey_slug) serializer = SurveySerializer(survey) response = get_hug_response(message='Organisation Active Survey Fetched Successfully', data=serializer.data) return Response(data=response, status=status.HTTP_200_OK) But, as you could all probably tell, the corresponding surveys.get('slug') fetch only returns the fields in the Survey model. Ideally, I would like to have some sort of fetch for each SurveyQuestion, and within that nested the SurveyQuestionAnswers Any pro-tips and pointers would be most appreciated. I have tried a few things, that only throw errors. I'm struggling to know what this … -
Initialize aditional object in DJango model instance and pass model instance
Some calculations became too complex to maintain inside model so i decided to move them out and break the code in several classes and modules. There's single class serving as a facade which i would like to have available in model instance to pass data to it. It is being constructed from model instance: class Calculator: def __init__(self, field1: date, field2: float): self.field1= field1 self.field2 = field2 @classmethod def from_django_model(cls, django_model_instance): field1 = django_model_instance.field1 field2 = float(django_model_instance.field2) Currently I call it inside each property on my model like so: class DjangoModel(models.Model): # initialize the calculator def calculator(self, group): return calculator.Calculator(self) # use it @cached_property def calculated_field(self): try: return self.calculator().calculation_method except AttributeError: return "Field not set!" I feel this is not a good solutions, since now on multiple methods I'm initializing calculator object multiple times. I would like to construct it once when model is initialized and then pass it model instance. Tried doing it with model manager, but model instance is not available with it. -
How to show balance in html to users who are registered users? [duplicate]
This question already has an answer here: How to show every user specific payment for them in django? 1 answer I have assigned some random numbers as a balance to every user who sign up but I am not able to show them in html page. How to do it? Maybe I have made some mistakes in python files also. I have added those balance(numbers) in my database. So please let me know. models.py class Payment(models.Model): payment_numbers = models.CharField(max_length=100) owner = models.ForeignKey(User, on_delete=models.CASCADE) views.py def payment(request): receiving1 = Payment.objects.filter(owner=request.user) for field in receiving1: field.payment_numbers context = { 'receiving1': receiving1 } return render(request, 'index.html', context) HTML page {% for numbers1 in receiving1 %} {% if numbers1 %} <li style="float: right;">Your Balance: Rs. {{numbers1.payment_numbers}}</li> {% endif %} {% endfor %} Python Shell >>> from users.models import Payment >>> Payment.objects.all() <QuerySet [<Payment: Payment object (1)>, <Payment: Payment object (2)>]> -
Duplicate client and process creating when selecting the number of process in django
This is my html file in this html I get the saved client and process list in DB, At that time got duplication. html <tbody> {% for object in emp_obj %} <tr> <td> {{ object.process.client }}<br /> </td> <td> {% for obj in emp_obj %} {% if obj.process.client == object.process.client %} {{ obj.process.process }}<br /> {% endif %} {% endfor %} </td> </tr> {% endfor %} </tbody> In views.py I fetch the Emp_Process list to based on the Emp_Profile ID and pass the emp_object to template views.py def Emp_CP_View(request, id): emp = Emp_Profile.objects.get(pk=id) print(emp) emp_obj = Emp_Process.objects.filter(username = emp) print(emp_obj) return render(request, 'employee_view.html',{'emp_obj' : emp_obj}) The below image is i got the duplication of the data -
How to send a HTML e-mail using Wagtail editor and Wagtail-Streamfield?
I want to integrate the functionality to generate a HTML site using Wagtail tools such as its editor and the Wagtail-Streamfield and send it as HTML email. Is there a straightforward way to render the Wagtail Page as html and send it using the Django email module? -
How to convert the numpy array with the wav file without writing to the disk?
sending usertext from web to tacotron create tts - > nunpy array - > file.wav ( x ) 3 i want create tts -> numpy array - > ( dont save ) -> playable data -> web playing !! def son_vo(get_text,get_speaker): global mySyns makedirs("logdir-tacotron2/generate") checkpoint_step = None num_speakers = 2 load_path = 'logdir-tacotron2/+_2019-08-05_08-05-17/' syn_speaker_id = 1 sample_path = "logdir-tacotron2/generate" audio = mySyns.synthesize(texts=[get_text],base_path=sample_path,speaker_ids=[get_speaker],attention_trim=True,base_alignment_path=None,isKorean=True)[0] print(type(audio)) return audio import synthesizer as syn def tts(request): output = tts2(request.GET['Text'],request.GET['speaker']) return HttpResponse(output) def tts2(userText,userVoice): data = syn.son_vo(userText,userVoice) return data -
Database normalization in django
I need an optimally normalized db structure to achieve the following req. models.py class Learning_Institute(models.Model): name = models.TextField() user = models.ManyToManyField(settings.AUTH_USER_MODEL) class Course(models.Model): title = models.CharField(max_length=50) instructor = models.ForeignKey(User, on_delete=models.PROTECT, related_name='courses_taught') institute = models.ForeignKey(Learning_Institute, on_delete=models.PROTECT, related_name='courses') I need the instructor field in the Course Table to be limited to the set of users in Learning_Institute instead of all the users int the system. How do i achieve this in the DB level? -
Django Model.objects.all() returning empty QuerySet in celery task
project/project/settings.py ... CELERY_BEAT_SCHEDULE = { 'find-subdomains': { 'task': 'subdiscovery.tasks.find_subdomains', 'schedule': 10.0 } } project/subdiscovery/tasks.py from __future__ import absolute_import, unicode_literals from celery import shared_task from subdiscovery.models import Domain @shared_task def test(): print(Domain.objects.all()) return 99 The celery worker shows an empty QuerySet: celery_worker_1 | [2019-08-12 07:07:44,229: WARNING/ForkPoolWorker-2] <QuerySet []> celery_worker_1 | [2019-08-12 07:07:44,229: INFO/ForkPoolWorker-2] Task subdiscovery.tasks.find_subdomains[60c59024-cd19-4ce9-ae69-782a3a81351b] succeeded in 0.004897953000181587s: 99 However, importing the same model works in a python shell: ./manage.py shell >>> from subdiscovery.models import Domain >>> Domain.objects.all() <QuerySet [<Domain: example1.com>, <Domain: example2.com>, <Domain: example3.com>]> -
How to handle login + FB login at the same time with django-allauth module?
Well.. I started to create simple app. Following official doc of Django, I created auth logic in separate app with name users, like this: users/urls.py: from django.urls import path, re_path, include from . import views urlpatterns = [ path('', include('django.contrib.auth.urls')), path('profile/', views.redirect_to_user_profile, name='redirect-user-profile'), re_path('profile/(?P<pk>\d+)/', views.UserProfileView.as_view(), name='user-profile'), path('register/', views.UserRegisterView.as_view(), name='user-register'), users/views.py: from django.shortcuts import render from django.http import HttpResponseRedirect from django.views import generic from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm # Create your views here. def redirect_to_user_profile(request): url = f'/users/profile/{request.user.id}' return HttpResponseRedirect(redirect_to=url) class UserProfileView(generic.DetailView): model = User template_name = 'user_profile.html' class UserRegisterView(generic.CreateView): form_class = UserCreationForm template_name = 'register.html' success_url = '/users/login' Everything was fine, so I decided to extent basic Django user, to add profile image for example (and more fields later) like this: users/models.py: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class ProfileUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_image = models.URLField() @receiver(post_save, sender=User) # Still don't know how, but next rows create ProfileUser when User is created def create_user_profile(sender, instance, created, **kwargs): if created: ProfileUser.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profileuser.save() def __str__(self): return f"{self.user}" Still working fine. Then I decided to add FB login, … -
How to "get" User that don't sign in yet?
I'm working on email activation, I do not want the user to login before they activate their email, so I set the active status as "false". The question is how do I get that user and make it True when they activation email. def activation_view(request, activation_key): if (SHA1_RE.search(activation_key)): print("acti is real") try: instance = EmailConfirmed.objects.get(activation_key=activation_key) except EmailConfirmed.DoesNotExist: instance = None raise Http404 if instance is not None and not instance.confirmed: page_message = ("ยืนยัน User เรียบร้อย") instance.comfirmed = True instance.activation_key = "Confirmed" instance.save() user.is_active = True? elif instance is not None and instance.comfirmed: page_message = ("User ถูกยืนยันไปแล้ว") else: page_message = "" context = {"page_message":page_message} return render(request, 'accounts/activation_complete.html',context) else: raise Http404 -
In Django REST Framework, how to get the "query parameter" sent by the previous page's hidden input?
I have an html page for listing the model "Descriptions", and at the end of it there's a button to go to the Description creation page, while sending the "character_id" that is intended to be a default initial value for the new Description (and I have set up the context so that the character_id would be there: <!--The code for listing the Descriptions--> <form action="{% url 'polls:description_detail_create_from_character' %}"> <input type="hidden" value="{{ serializer.context.character_id }}" name="character_id"> <input type="submit" value="New Description"/> </form> On the browser, if I click "New Description", it will bring me to: http://localhost:8000/polls/description_detail_create_from_character/?character_id=3 However, then I don't know how can I get this "character_id" from description_detail_create_from_character (the next page)'s template. Thought it could be request.query_params.get('character_id', None), but doesn't work. By debugging, I can find the dict query_params, however, there's nothing in it. Just don't know how can I get this character_id=3. It's nowhere to be found in the {% debug %} either. Is something more to be done in the Serializer? Or View? Is this ?character_id=3 here actually a query parameter here? If it is not then what it is? Code: Serializers.py: # The serializer for the creation page class DescriptionCreateFromCharacterSerializer(DescriptionSerializer): author = serializers.HiddenField(default=serializers.CreateOnlyDefault(DefaultFieldCurrentUser())) # This works btw, unlike the …