Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to connect to MockServer from Django Docker container
I've setup a Django container along with a MockServer container running in docker-compose. I can access the MockServers' endpoints fine using postman, but when doing a request from the python container I get an error: requests.exceptions.ConnectionError: HTTPConnectionPool(host='localhost', port=1080): Max retries exceeded with url: /devices (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f6d83e4fa60>: Failed to establish a new connection: [Errno 111] Connection refused')) Here is my MockServer.properties: mockserver.maxSocketTimeout=120000 mockserver.dynamicallyCreateCertificateAuthorityCertificate=true mockserver.directoryToSaveDynamicSSLCertificate=. mockserver.sslCertificateDomainName=localhost mockserver.sslSubjectAlternativeNameDomains=www.example.com,www.another.com mockserver.sslSubjectAlternativeNameIps=127.0.0.1 mockserver.enableCORSForAPI=true mockserver.enableCORSForAllResponses=true mockserver.corsAllowHeaders=Cache-Control, Postman-Token, Host, User-Agent, Accept, Accept-Encoding, Connection, Allow, Content-Encoding, Content-Length, Content-Type, ETag, Expires, Last-Modified, Location, Server, Vary, Authorization mockserver.corsAllowMethods=CONNECT, DELETE, GET, HEAD, OPTIONS, POST, PUT, PATCH, TRACE mockserver.corsAllowCredentials=true My code for doing the request looks like this: return requests.get( URL + 'devices', headers={'Content-Type': 'application/json', 'Authorization': 'Basic ' + auth.decode('utf-8')} ) MockServer url is http://localhost:1080, and it works when using any other external url. ANy idea what can cause this? -
Custom template for database query in Django templates always returns true or isnt working
I am trying to write a custom template that can query the database based on it context, however, It seems it always returns false or it's returning nothing: my custom tag is (in ibuilder.py): @register.simple_tag(takes_context=True) def is_bookmarked(context): request = context['request'] id = hashids.decode(context['hid'])[0] if context['t'] == 'post': return BookmarkPost.objects.get(user__id=request.user.id, obj__id=id).exists() elif context['t'] == 'blog': return BookmarkBlog.objects.get(user__id=request.user.id, obj__id=id).exists() Inside my base.html I have: {% include 'main/bookmark/bookmark.html' with hid=blog.get_hashid t="blog" %} and my bookmark.html is: {% load ibuilder %} <form class="bookmark-form" method="POST"> {% csrf_token %} {% if not is_bookmarked %} <button class="p-0 etbm_btnall btn btn-m" type="submit" data-url="{% url 'main:add-bookmark' hid=hid obj_type=t %}" ><svg class="bi mr-1 bi-bookmark" width="1em" height="1em" viewBox="0 0 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" d="M8 12l5 3V3a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v12l5-3zm-4 1.234l4-2.4 4 2.4V3a1 1 0 0 0-1-1H5a1 1 0 0 0-1 1v10.234z"/> </svg></i></button> {% else %} <button class="p-0 btn etbm_btnall btn-m" type="submit" data-url="{% url 'main:add-bookmark' hid=hid obj_type=t %}" ><svg class="bi mr-1 bi-bookmark-fill" width="1em" height="1em" viewBox="0 0 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" d="M3 3a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v12l-5-3-5 3V3z"/> </svg></i></button> {% endif %} </form> The issue seems to be that is_bookmarked always seems to be returning false, … -
Copy a folder from server to Azure blob using django-storage
How can I upload a folder (media_root/folder) which contains subfolder and files in it to Azure blob container? I can upload a file to Azure blob container using this: from django.core.files.storage import default_storage f = open('media_root/folder/file.csv', 'rb') default_storage.save(path, f) I have set AzureStorage class in my settings.py. DEFAULT_FILE_STORAGE = 'storages.backends.azure_storage.AzureStorage' Any help would be much appreciated. -
How can I sort posts by date in my web application in Django?
I have a web application and I was trying to order it by most recent date, that is, the most current above and the oldest dates below, but for some reason it orders me the other way around and on other computers it orders well, the strange thing is that on my local server it is fine, it orders me as I want but at the time of showing it on the website it shows as I had mentioned before. models.py from django.db import models class Publicacion(models.Model): foto = models.ImageField() titulo = models.CharField(max_length=200) contenido = models.TextField() fecha = models.DateField(auto_now_add=True) contenido_largo = models.TextField(max_length=10000, default='', null=True, blank=True) def __str__(self): return self.titulo views.py class ListarPublicaciones(ListView): model = Publicacion template_name = 'Publicacion/listarPublicaciones.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if self.request.user.is_authenticated: pedidos = Pedido.objects.filter(cliente = self.request.user).aggregate(Sum('cantidad')) context['Pedido'] = pedidos context['object_list'] = Publicacion.objects.all().order_by('-fecha') return context I have tried with order_by('-fecha__year','-fecha__month','-fecha__day') html <section class="py-5"><!-- Page Content --> <div class="container"><!-- Container página principal --> <div class="row"> <div class="col-md-12"> <div class="panel"> {% for p in object_list %} <div class="row"> <br> <div class="col-md-3 col-sm-3 text-center"> <a class="story-img" href="{% url 'publicacion:detallePublicacion' p.pk %}"> <img src="{{p.foto.url}}" class="rounded" style="width: 250px;"></a> </div> <div class="col-md-8 col-sm-9"> <a class="subt" href="{% url 'publicacion:detallePublicacion' p.pk %}"><h2>{{p.titulo}}</h2></a> <div class="row"> … -
Convert 12,34 into 12.34 in Django template for css purposes
I have to deal with django, so here goes my question. I have a template where I want to calculate values and then use them in css. It looks like: padding-top: {{ VAL1|divide:VAL2|multiply:VAL3 }}px It calculates the value I need albeit in some strange fashion via filters, I am ok with that since I am already dealing with django :( The problem is that the result of calculation has comma inside like 12,34 whereas 12.34 is needed for css to work properly - padding-top: 12,34px isn't valid css due to the comma (I use google chrome). I tried to use floatformat filter - no success. It looks like a simple thing but I cannot wrap my head around it... -
Django FieldError: Cannot resolve keyword 'custom_field' into field. Choices are:
I'm using Django REST 2.2 with rest-auth. I have a custom user model with an additional field "custom_field". I'm trying to select all users where custom_field="something". However when I browse to /api/accounts I'll get the following error: "django.core.exceptions.FieldError: Cannot resolve keyword 'custom_field' into field. Choices are: auth_token, course, date_joined, email, emailaddress, first_name, groups, id, is_active, is_staff, is_superuser, last_login, last_name, logentry, password, socialaccount, user_permissions, username, userprofile" So it seems like my custom_field is not recognized. What did I do wrong? user_profile/models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) customField = models.CharField(max_length=255, blank=True, null=True) user_profile/serializers.py class UserSerializer(UserDetailsSerializer): custom_field = serializers.CharField(source="userprofile.custom_field", allow_blank=True, required=False) class Meta(UserDetailsSerializer.Meta): fields = UserDetailsSerializer.Meta.fields + ('custom_field') def update(self, instance, validated_data): custom_field = profile_data.get('custom_field') instance = super(UserSerializer, self).update(instance, validated_data) # get and update user profile profile = instance.userprofile if profile_data: if custom_field: profile.custom_field = custom_field profile.save() return instance user_profile/views.py class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer def list(self, request): queryset = User.objects.filter(custom_field="something") serializer = UserSerializer(queryset, many=True) return Response(serializer.data) project/urls.py router = routers.DefaultRouter() router.register('accounts', UserViewSet) urlpatterns = [ path('admin/', admin.site.urls), # This is used for user reset password path('', include('django.contrib.auth.urls')), path('rest-auth/', include('rest_auth.urls')), path('rest-auth/registration/', include('rest_auth.registration.urls')), path('account/', include('allauth.urls')), path('api/', include(router.urls)), rest_auth/serializers.py (dependency) class UserDetailsSerializer(serializers.ModelSerializer): """ User model w/o password """ class Meta: model … -
problem when adding a new form with JS in django
I am facing a problem when adding dynamically a new form in a table with JS. The formset is generated. I can add a new line, but when I submit my formset, the last line is not detected, the error gives me : Formset errors sont: [{}, {}, {}, {'num': ['This field is required.'], 'description': ['This field is required.']}] Do you have any clues what should be the problem? :( Thanks a lot! Regards models.py class Link1(models.Model): num=models.IntegerField() description=models.CharField(max_length=100) class Case(models.Model): link=models.ManyToManyField(Link1,related_name='cases') forms.py class Form1(forms.Form): num=forms.IntegerField(label=None,widget=forms.Select(choices=liste_1,attrs={'class': 'custom-select text-white','style':'background-color:#063c5c'})) description=forms.CharField(label=None,max_length=100, widget=forms.Select(choices=liste_description,attrs={'class': 'custom-select text-white', 'style':'background-color:#063c5c'})) views.py def validation2(request, case_id): case = get_object_or_404(Case, id=case_id) case_id2=case.id formset1=formset_factory(Form1,extra=0) if request.method=="POST": myform = formset1(request.POST) if myform.is_valid(): case.link.clear() for f in myform: cd=f.cleaned_data print("cd:") print(cd) #On va effacer et réaffecter tout! numero=int(cd['num']) desc=cd['description'] obj,boleensiexiste=Link1.objects.get_or_create(num=numero,description=desc) case.link.add(obj) case.save() return redirect(reverse('validation1', kwargs={'case_id': case_id2})) else: liste_initiales=[] for link in case.link.all(): liste_initiales.append({'num': link.num ,'description':link.description}) myform=formset1(initial=liste_initiales) print(myform) context={'myform':myform, 'case':case} return render(request,'analyzis.html', context) html <table id="TableRecap" class="table order-list table-borderless text-white p-0 mx-5" style="background-color:#063c5c"> <thead> <tr> <th scope="col" ><div class="text-center"><h5></h5></div></th> <th scope="col" ><div class="text-center"><h5></h5></div></th> <th scope="col"> </th> </tr> </thead> <form action="{% url "validation2" case.id%}" method="post"> {% csrf_token %} {{ myform.management_form }} <tbody id="myTableBody"> {% for formz in myform %} <tr><td> {{ formz.num }} </td><td> {{ … -
Django Port from Postgres to MariaDB manage.py migrate error SQL Syntax Error 1064
I am porting my Django application from Postgres to MariaDB and receive the following error when doing the migration step: django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '[20] NOT NULL, `last_update` datetime(6) NOT NULL, `commited` bool NOT NULL, ...' at line 1") All the standard Django tables are created and my first model table is created. But I never get beyond that step. My models are all of the following style: class Country(models.Model): name = models.CharField(max_length=100, unique=True, help_text=_('This is the full name of the country'), verbose_name=_('Country'), ) alternate_name = models.CharField(max_length=100, null=True, blank=True, help_text=_('This is the alternate name - often abbreviation - of the country'), verbose_name=_('Country alternate name'), ) iso_numeric = models.DecimalField(max_digits=3, decimal_places=0,null=True, help_text=_('This is the ISO numeric code of the country'), verbose_name=_('ISO numeric code'), ) iso_alpha = models.CharField(max_length=3, null=True, blank=True, help_text=_('This is the ISO alpha code of the country'), verbose_name=_('ISO alpha code'), ) last_update = models.DateTimeField(auto_now_add=True, help_text=_('This is the timestamp of the last update'), verbose_name=_('Timestamp last update'), ) last_update_id = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL, editable=False, help_text=_('This is the user making last update'), verbose_name=_('User making last update'), ) committed = models.BooleanField(default=False, editable=False, … -
django-rest-framework-social-auth requires a client secret for convert token
I am making an Android application with a Django based backend. The Django server has a REST API to serve user data which I want to protect. I only want my users to log in via Google (or FB which I'm going to implement in the future). I am using django-rest-framework-social-auth to implement the authorization in the backend. So the flow as I understand is like this: The client (my android application), does the whole Google OAuth2.0 flow and obtains the access token The the client then wants to convert the Google access token with one with which it can access my backend server API endpoints. To do this it calls the convert-token API endpoint implemented in django-rest-framework-social-auth Now that it has the API access token, it can include that in the header of all further API calls and receive the private data. Now my concern is, the django-rest-framework-social-auth convert-token endpoint also needs the client-id and client-secret generated by django-oauth for the application. So I will have to store the client-secret somewhere in my mobile app, which entirely defeats the purpose of authenticating whether the request came from the app or not, because someone can decompile the apk and get … -
How to use default manager in django migrations with inherited models?
I have a model Baz that's inheriting from an abstract model Bar which is inheriting as well from an other abstract model Foo. from django.db import models class BarManager(models.Manager): pass class Foo(models.Model): attr1 = models.CharField(max_length=20) objects = models.Manager() class Meta: abstract = True class Bar(Foo): attr2 = models.CharField(max_length=20) bar_objects = BarManager() class Meta: abstract = True class Baz(Bar): attr3 = models.CharField(max_length=20) when running a data migration I want to be able to use the default manager Baz.objects: # Generated by Django 3.0.7 on 2020-06-23 15:57 from django.db import migrations def update_forward(apps, schema_editor): Baz = apps.get_model('migration_manager', 'Baz') Baz.objects.filter(attr1='bar').update(attr1='baz') class Migration(migrations.Migration): dependencies = [ ('migration_manager', '0001_initial'), ] operations = [ migrations.RunPython(update_forward), ] but it's not available as I'm getting: File "/home/user/code/django_issues/migration_manager/migrations/0002_update_content.py", line 8, in update_forward Baz.objects.filter(attr1='bar').update(attr1='baz') AttributeError: type object 'Baz' has no attribute 'objects' This is the initial migration that gets created automatically # Generated by Django 3.0.7 on 2020-06-23 16:13 from django.db import migrations, models import django.db.models.manager class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Baz', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('attr1', models.CharField(max_length=20)), ('attr2', models.CharField(max_length=20)), ('attr3', models.CharField(max_length=20)), ], options={ 'abstract': False, }, managers=[ ('bar_objects', django.db.models.manager.Manager()), ], ), ] in there there is the managers section … -
Updating Variations quantities for products to cart not working properly
I have an issue with the order summary page when I try to update the quantity of items, if I added to the cart 3 different attributes of an Item small, medium, large whenever I update the quantity for any of the 3 variants the first one is the only one updated, I know the reason but I can't figure out how to fix it, the problem is that when the item variation quantity is updated it reflects only on the item. slug there is not value that distinguished each item variation. I assume that the views.py related to adding and removing single items is correct as when I add different variations for the same item from the product detail page it is correctly reflected in the order summary template. I have recently added the post method to the order summary template but still, it is not working. Here is the models.py class Item(models.Model): title = models.CharField(max_length=100) class Variation(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) category = models.CharField( max_length=120, choices=VAR_CATEGORIES, default='size') title = models.CharField(max_length=120) objects = VariationManager() class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) variation = models.ManyToManyField(Variation) here is the views.py class OrderSummaryView(LoginRequiredMixin, … -
CSS not working with html file in django, why is it not working?
My CSS file does not seem to be working in Django and I am not sure why. I have tried many different ways to get it to work but it's still not working. I have added {%load static%}on top of the HTML file and my css file is named main.css which is in a folder called static. I have also added the line <link rel="stylesheet" type= "text/css" href="{% static 'css/main.css' %}" > to my html file. Also in my setting.py file I have added this line STATICFILES_DIR=[ "/Users/yaminhimani/Desktop/tweetybird/static", ] in order to find the CSS file. After doing all this why would the styling still now show up for my website? -
Best architecture for distributed Dockerized web app and API calls to other Docker containers [closed]
My web app consists of several coponents: A Django web app in a docker container Several docker containers that are frequently called by the Django web app (some more, some less frequently) A database (postgresql) to which the Django web app will connect to I want to deploy such a web app on AWS, such that we have very low latency in many geographic regions (even with heavy load in some regions, some regions with less heavy load) and also the API call latency should give you answers in real-time (a few ms latency even if these Docker containers are frequently accessed). Is that possible on AWS and if so, what kind of architecture would you use for making this web app fulfil all the requirements? -
_wrapped_view() missing 1 required positional argument: 'request' in django
I have a view just like this : @login_required(login_url='account:login') def editpost(request,user_id,post_id): if request.user.id == user_id: post = get_object_or_404(Posts,pk=post_id) if request.method == 'POST': form = editpost(request.POST,instance=post) if form.is_valid(): slug = form.cleaned_data.get("body") slug2 = slug[:30] num_rand = random.randint(7486,20000) slug3 = slug2 + "-" + str(num_rand) ep = form.save(commit=False) ep.slug = slugify(slug3) ep.save() return redirect('account:dashboard',user_id) else: form = editpost(instance=post) return render(request,'editpost.html',{'form':form}) else: return redirect('Posts:index') and form.py : class editpost(forms.ModelForm): class Meta: model = Posts fields = ['body'] when i open editpost url i got this error:_wrapped_view() missing 1 required positional argument: 'request' full track back: AttributeError at /editpost/1/3 'QueryDict' object has no attribute 'user' Environment: Request Method: GET Request URL: http://localhost:9999/editpost/1/3 Django Version: 3.0.6 Python Version: 3.8.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'posts.apps.PostsConfig', 'account.apps.AccountConfig', 'crispy_forms'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\Nima Aram\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Nima Aram\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Nima Aram\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Nima Aram\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\Nima Aram\Desktop\wui\posts\views.py", line 61, in editpost form = editpost(request.POST,instance=post) File "C:\Users\Nima Aram\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\decorators.py", line 20, in _wrapped_view … -
ImageField is not uploaded in Django
I'm struggling with uploding an image using Django. Here is my model, where i have the image field: class User(AbstractBaseUser, PermissionsMixin): USERNAME_FIELD = 'email' ... photo = models.ImageField(upload_to="images/", default=None, blank=True, null=True) I've read another posts on Stack overflow, and i found that in settings.py i have to define MEDIA_ROOT and MEDIA_URL. This is what i have in my file: MEDIA_URL = '/images/' MEDIA_ROOT = '/home/anamaria/workspace/AllFest2/festivals/user/images/' And now, in url.py i need to define my urlpatterns: urlpatterns = [ . . . ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I believe that the path is not given the right way. But i don't know why. How should i do it?( the user folder is in 'AllFest2/festival', which is my project's root. user ├── admin.py ├── api │ ├── __init__.py │ ├── permissions.py │ ├── __pycache__ │ │ ├── __init__.cpython-36.pyc │ │ ├── permissions.cpython-36.pyc │ │ ├── serializers.cpython-36.pyc │ │ └── views.cpython-36.pyc │ ├── serializers.py │ └── views.py ├── images ├── __init__.py ├── manager.py ├── migrations │ ├── 0001_initial.py │ ├── __init__.py │ └── __pycache__ │ ├── 0001_initial.cpython-36.pyc │ └── __init__.cpython-36.pyc ├── models.py ├── OCR.py -
Cannot change superusers own django admin inline
I have recently updated from django 2.0.4 to 3.0.5. I have a UserAdmin with the following inline: class PreferencesInline(admin.StackedInline): model = Preferences can_delete = False classes = ['collapse'] When I login as a superuser, I can change the preferences of other users through the inline, but not my own. Why is that? On our server with django 2.0.4 I can both change other users preferences but also my own preferences through the inline. I could not find any explanation for this strange behaviour... -
Django2.8/Python3 - Make parent-child work asynchronously
I call a Django(python) function through ajax call. That function has a child function which is responsible for sending an SMS. I noticed that it takes too long for the ajax call to return back if SMS-function stuff takes time to return. I want the main function to not wait for this SMS-function because it doesn't really affect the processing of the main function. I feel I need to use async stuff. I read few articles but I really don't know how to implement that with API request code below. They use things like these loop = asyncio.get_event_loop() client = aiohttp.ClientSession(loop=loop) I am new to this and I don't know how to adjust with my piece of code. MAIN Function(ajax) @login_required def selected_object_action(request): .... .... success_or_failure = send_sms(original_qs, status) The CHILD Function i.e send_sms() def send_sms(list, status): ... ... conn = http.client.HTTPConnection("api...") payload = {....} payload = json.dumps(payload) headers = { 'authkey': tr_auth, 'content-type': "application/json" } ## this is not a good way to handle errors. We must have a way to know something went wrong. try: conn.request("POST", "/api/...", payload, headers) res = conn.getresponse() data = res.read() response = data.decode("utf-8") response = ast.literal_eval(response) return response['type'] == 'success' except: print('An error … -
How can I dynamically change the image size or size in bytes based on GET parameters from the user?(Django)
I'm trying to create a simple project where you can upload images and display a list of them. I want to add the ability to change the image size/compression based on GET parameters. How do I do this? Urls.py urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('images.urls')), path('upload/', upload, name='upload'), path('', list, name='list') ] + static('image/', document_root=settings.MEDIA_ROOT) Image upload: def upload(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): temp_doc = request.FILES['docfile'] _, extension = str(temp_doc).split('.') newdoc = Document(docfile=ContentFile(temp_doc.read(), hashlib.md5(temp_doc.read()).hexdigest()+f'.{extension}')) newdoc.save() return HttpResponseRedirect(reverse('list')) else: form = DocumentForm() return render(request, 'upload_image.html', {'form': form}) Models.py class Document(models.Model): docfile = models.FileField(upload_to='documents/%Y/%m/%d') I can't even figure out how to link the view to the URLs where the downloaded files are stored(media). UPD: I can redirect user to single image, but I don't know how to write a handler(view) to work with this image. UPD2: I forgot about an important clarification, I want the image size to change only in the browser. The database entry should not be affected. -
django: how get some detail with python-gitlab library
hello Im amateur and i need some help I want to get open issue and open mergerequest from gitlab I use python-gitlab to connect gitlab but i problem with save them to database I created 2 models: issue and merges from django.db import models from django.contrib.postgres import fields as pgfields class Merge(models.Model): merge_id = models.IntegerField(primary_key= True) issue_merge_id = models.ForeignKey('Issue', on_delete=models.CASCADE) the_json = pgfields.JSONField(default='SOME STRING') class Issue(models.Model): issue_id = models.IntegerField(primary_key= True) and my custom manage command: from django.core.management.base import BaseCommand import gitlab import json from call.models import Merge class Command(BaseCommand): help = 'Getting issue and merge request' def handle(self, *args, **kwargs): project = gitlab.Gitlab( 'https://*********', private_token='**************' ) issues = project.issues.list(state= 'opened') merges = project.mergerequests.list(state= 'opened') issueIds = [] mergeIds = [] for issue in issues: issueIds.append(issue.id) for merge in merges: mergeIds.append(merge.id) json_dic = { "issues": issueIds, "merges": mergeIds } data = json.dumps(json_dic) Merge.objects.create(the_json= data) a = Merge.objects.all() for merge in a: print(merge.the_json) how I can fix and solve it? I want to get issue.id and merge.id after that save them to issue_id and merge_id and get json and save it to the_json afterthat i want to compare : if next data will come from gitlab isnt new data =data update and … -
Django REST Framework relations
when i make my api using the Hyper Linked method i get this error. ImproperlyConfigured at /api/order/ Could not resolve URL for hyperlinked relationship using view name "customer-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. Request Method: GET Request URL: http://127.0.0.1:8000/api/order/ Django Version: 3.0.7 Exception Type: ImproperlyConfigured Exception Value: Could not resolve URL for hyperlinked relationship using view name "customer-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. This is my serializer.py: from rest_framework import serializers from api.models import * class OrderSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Order fields = ('id', 'customer', 'orderid', 'date', 'status') It cant find the relation between customer and order in the order serializer, when i write the code without the customer field it works. Is there any way i can query this? And this is my views.py: from django.shortcuts import render from rest_framework import viewsets from api.models import * from api.serializer import * class OrderView(viewsets.ModelViewSet): queryset = Order.objects.all() serializer_class = OrderSerializer I get the same error when i try to access the orderitem api and the shipping adress api. … -
Is it possible to pass extra argument using django-rest-multiple-model
I am using django-rest-multiple-model along with django rest framework to work with multiple model in a single viewset. I need to pass some extra argument like user_id to the serializer. Using django rest framework we can send in the following way: Code: (Using Django Rest Framework) serializer = PollDetailSerializer(context1,context={"user_id": request.user.user_id}, many=True) Now I need to pass same argument using django-rest-multiple-model. In the docs i have seen the following way: querylist = ({'queryset': question, 'serializer_class': PollDetailSerializer,'label': 'Poll_details',}) Your response will help me alot. -
django rest-framework error : AttributeError: type object 'SignUp' has no attribute 'get_extra_actions'
Im new to django and rest-framework, hope you can help me. Im trying to signin / signup with user credentials and Im getting this error while trying to pass a post req to /api/user/sign_in and to /api/user/sign_up, the error: extra_actions = viewset.get_extra_actions() AttributeError: type object 'SignUp' has no attribute 'get_extra_actions' here is my urls: from django.contrib import admin from django.urls import include,path from .routers import router from django.views.generic import TemplateView from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView urlpatterns = [ path('admin/', admin.site.urls), path('api/token/refresh', TokenRefreshView.as_view()), path('api/token/', TokenObtainPairView.as_view()), path('api/', include(router.urls)), path('', TemplateView.as_view(template_name = 'index.html')), ] here is the routes: from rest_framework import routers from user.viewsets import SignIn, SignUp from todo.viewsets import TodoViewSet router = routers.DefaultRouter() # todo paths router.register(r'todo', TodoViewSet, basename = 'todo') # user paths router.register(r'user/sign_in', SignUp, basename='user_sign_in') router.register(r'user/sign-up', SignIn, basename='user_sign_up') here is my serializers from rest_framework import serializers from django.contrib.auth.models import User from django.contrib.auth import authenticate class SignUpSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('_id', 'username', 'email', 'password') extra_kwarg = { 'password' : { 'write_only' : True }} def create(self, validated_data): user = user.objects.create_user(validated_data['username'], validated_data['email'], validated_data['password'], validated_data['re_password']) if password != re_password: raise serializers.ValidationError('Passwords Must Match') return user class SignInSerializer(serializers.ModelSerializer): class Meta: model = User fields: ('username', 'password') extra_kwarg = { 'password' … -
'django' is not recognized as an internal or external command
New to PyCharm and Django, I've looked through online for this solution for a few hours already, nothing seems to work. The usual: python -m django-admin startproject mysite does not seem to work if my cmd directory is at C:\Users\...\PycharmProjects\ On the other hand, if I use cd C:\Users\...\AppData\Local\Programs\Python\Python38\Scripts before reentering the former code, I get the exact results that I want. Any idea how to fix this? -
How to write the answering page view for django quiz app?
I am wrting a mcq app in django and i am a complete beginner. I am having an issue. I am stuck on writing the page for answering a quiz. Every time a user takes the test,i want to create a new Sitting object, and i want to display a questions-choices form of the quiz and use the choices from each questions to fill the user_answer textfield of the Sitting object, all in the same view. How can I do that? models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Test(models.Model): title = models.CharField(max_length=100) date_posted=models.DateTimeField(default=timezone.now) creator=models.ForeignKey(User,on_delete=models.CASCADE) total_marks=models.IntegerField(default=0) def get_total_marks(self): for question in self.question_set.all(): self.total_marks+=question.Marks return self.total_marks def get_correct_answer_list(self): correct_answers=[] for question in self.question_set.all(): for choice in question.choice_set.all(): if choice.is_correct: correct_answers.append(choice) return correct_answers def __str__(self): return self.title class Question(models.Model): test=models.ForeignKey(Test,on_delete=models.CASCADE) question_text = models.CharField(max_length=200) Marks = models.IntegerField(default=2) def get_answer_list(self): answer_list=[] for choice in enumerate(self.choice_set.all()): answer_list.append(choice) return answer_list def __str__(self): return self.question_text class Choice(models.Model): question=models.ForeignKey(Question,on_delete=models.CASCADE) choice_text=models.CharField(max_length=200) is_correct=models.BooleanField() def __str__(self): return self.choice_text class Sitting(models.Model): student=models.ForeignKey(User,on_delete=models.CASCADE) test=models.ForeignKey(Test,on_delete=models.CASCADE) score=models.IntegerField(default=0) taken_time=models.DateTimeField(default=timezone.now) user_answers=models.TextField(blank=True,default='') def calculate_score(self): user_answers_list=self.user_answers.split(',') correct_answers_list=self.test.get_correct_answer_list() for (answer,correct) in zip(user_answers_list,correct_answers_list): if answer==correct.choice_text: self.score+=correct.question.Marks return self.score def get_absolute_url(self): return "/%s/result/"%self.id def __str__(self): return self.student.username+' took '+self.test.title views.py from django.shortcuts import render,get_object_or_404 from django.views … -
Email Server to run sql query on a postgresql attached to django
I'll give some information about my setup although it may be somewhat arbitrary to the question. I'm using django and django-rest-framework hosted on heroku as the backend to a flutter app. I'm using the heroku postgres add-on for the database. My objective is to set up user email validation system but in a way that is slighty unconventional for reasons I wont get into. I'd like to have users send an email to a specified adress, and on every email that comes in run a simple update sql query to set that user as active. No assistance is needed with the query. I'm looking for suggestions for an email server that might make this possible. If I can use the django ORM to do this, even better, but not neccesary. I've been looking into vba on outlook, but office 365 pushes alot of features at cost that I'm not interested in. If you could point me in the right direction of making a vba macro to get the job done that would be great, but other ideas are welcome. Any suggestion is appreciated. Thanks for the help.